Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between these two below?

Tags:

java

regex

System.out.println(matcher.group(1));
System.out.println(matcher.group());

I like to know what's the difference between the above two codes. I get different outputs. Can anybody elaborate on this?

Thanks

like image 922
giri Avatar asked Mar 23 '26 04:03

giri


1 Answers

The call to group() gives you the entire string that matched, whereas group(1) gives you the first parenthesized "Capturing" group (or more generally, group(n) will give you the n'th capturing group, counting left/opening parenthesis, starting from 1).

So for example, if you had an input string like this:

The quick brown fox

And you matched against the following regular expression (without the quotes):

"The (\\w+)"

Then group() would give you "The quick" and group(1) would give you "quick".

For more details on how all of this regular expression stuff works in Java, look See the java.util.regex.Matcher JavaDoc.

like image 153
Adam Batkin Avatar answered Mar 24 '26 18:03

Adam Batkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!