What's the difference between these two below?
System.out.println(matcher.group(1));
System.out.pri开发者_如何学运维ntln(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
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.
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.
The API doc is a very good place to look first.
精彩评论