user3672700
user3672700

Reputation: 162

Using Java and regex, how can I capture an uncertain(?) group?

Let's suppose I have this regex:

Hello\smy\sname\sis((PETER)|(HARRY)|(EMMA))(and\smy\sage\sis(\d+))?

Capturing the names is pretty simple, I would just write something like this:

if(matcher.group(1).equals(matcher.group(2)) {
  String str = matcher.group(2);
}

...

However for the age:

if(!matcher.group(5).isEmpty()) {
  int age = matcher.group(6);
}

This only works if the text the pattern is working on actually has the age part, if it doesnt, an error pops. So how can I capture the uncertain group?

Upvotes: 1

Views: 63

Answers (2)

David Conrad
David Conrad

Reputation: 16359

Your regex is a bit strange. I assume you only want to capture the name and the age. There is no reason to put parentheses around each individual name, or to make the optional second part a capturing group (unless you have some need to see that whole part of the sentence, and not just the age itself; but the age is the only part that can vary, the rest being a constant string).

Also, it isn't possible with this regex to put a space before or after the name, which is odd. I would think you would want a regex like this instead:

Hello\smy\sname\sis\s(PETER|HARRY|EMMA)(?:\sand\smy\sage\sis\s(\d+))?

Notice that the second have has been made a non-capturing group by putting ?: after the opening parenthesis. The name will now be group 1, and group 2 will be null if the second half was not provided, otherwise it will contain the digits of the age.

For example, "Hello my name is EMMA and my age is 21" will yield:

  • Group 1: EMMA
  • Group 2: 21

Don't forget to double the backslashes when putting the regex into a string in your Java source code.

Upvotes: 2

Stefan Gärtner
Stefan Gärtner

Reputation: 145

If an optional group doesn't exist in your input string, the group method returns null. Therefore an NullPointerException is probably thrown in your if statement. Instead check if matcher.group(5) is null.

Upvotes: 2

Related Questions