Hemã Vidal
Hemã Vidal

Reputation: 1882

What's the regex to capture values which init string until end word?

My Entries:

String e1 = "MyString=1234 MyString=5678";
String e2 = "MyString=1234\nMyString=5678";

What i'm doing:

String pattern = "MyString=(.*)";
Pattern patternObj = Pattern.compile(pattern);
Matcher matcher = patternObj.matcher(e1);  //e1 or e2
if (matcher.find()) {
    System.out.println("G1: " + matcher.group(1));
    System.out.println("G2: " + matcher.group(2));
}

What i want in output:

G1: 1234
G2: 5678

Upvotes: 2

Views: 1039

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

The easiest "quick fix" is to replace . (any char but a newline) with \w (a letter, digit or an underscore):

String pattern = "MyString=(\\w*)"; // <---- HERE
Pattern patternObj = Pattern.compile(pattern);
Matcher matcher = patternObj.matcher(e1); 
if (matcher.find()) {
    System.out.println("G1: " + matcher.group(1));
    System.out.println("G2: " + matcher.group(2));
}

Now, MyString=(\\w*) matches a MyString= substring and matches and captures any 0 or more letters, digits or underscores after it not matching any whitespace, punctuation, and other non-word chars.

NOTE: If you need to match any chars but whitespace, you may use \S instead of \w.

Upvotes: 1

Malcolm G
Malcolm G

Reputation: 614

If it will always be numbers, you could use this as your regex:

String pattern = "MyString=([0-9]*)";

If it will contain letters as well as numbers, Wiktor Stribizew's comment is very helpful in the original post. He said to use \w which matches on word characters.

Upvotes: 1

shmosel
shmosel

Reputation: 50726

There's only one group that will be matched multiple times. You have to keep matching and printing group 1:

int i = 0;
while (matcher.find()) {
    System.out.println("G" + (++i) + ": " + matcher.group(1));
}

Also, you need to update your pattern so it doesn't match the next MyString. You can use \d+ or \w+ or [^\s]+, depending on the type of values you're matching.

Upvotes: 2

Related Questions