Java Reference
In-Depth Information
As you see, it's easy to number the capturing groups as long as you can count left parentheses. Group 1
is the same as Group 0 because the whole regular expression is parenthesized. The other capturing groups in
sequence are defined by
(B)
,
(C(D))
,
(D)
, and
(E)
.
To retrieve the text matching a particular capturing group after the
find()
method returns
true
, you call
the
group()
method for the
Matcher
object with the group number as the argument. The
groupCount()
method for the
Matcher
object returns a value of type
int
that specifies the number of capturing groups
within the pattern — that is, excluding group 0, which corresponds to the whole pattern. Therefore, you have
all you need to access the text corresponding to any or all of the capturing groups in a regular expression.
TRY IT OUT: Capturing Groups
Let's modify our earlier example to output the text matching each group:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TryCapturingGroups {
public static void main(String args[]) {
String regEx = "[+|-]?(\\d+(\\.\\d*)?)|(\\.\\d+)";
String str = "256 is the square of 16 and -2.5 squared is 6.25 " +
"and -.243 is less than
0.1234.";
Pattern pattern = Pattern.compile(regEx);
Matcher m = pattern.matcher(str);
while(m.find()) {
for(int i = 0; i <= m.groupCount() ; i++) {
System.out.println(
"Group " + i + ": " + m.group(i)); // Group i