tags:

views:

118

answers:

3
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

+2  A: 

I point you to the JavaDocs for Matcher

group():

Returns the input subsequence matched by the previous match

group(int):

Returns the input subsequence captured by the given group during the previous match operation.

KG
Please use `> ...` to blockquote.
KennyTM
@KennyTM Done :-)
KG
+1  A: 

The API doc is a very good place to look first.

Michael Borgwardt
+7  A: 

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.

Adam Batkin
This regular expression is missing something, didn't you mean "`The (\\w+)`" ? (and technically speaking, it will not match - `matches()`, it will be found - `find()` )
Carlos Heuberger
Updated to add the backslashes, and you are right about `matches()` versus `find()`.
Adam Batkin