Java Reference
In-Depth Information
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 is the number of
capturing groups within the pattern - that is, excluding group 0, which corresponds to the whole
pattern. You therefore 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 substring
}
}
This produces the output:
Group 0: 256
Group 1: 256
Group 2: null
Group 3: null
Group 0: 16
Group 1: 16
Group 2: null
Group 3: null
Group 0: -2.5
Group 1: 2.5
Group 2: .5
Group 3: null
Group 0: 6.25
Group 1: 6.25
Group 2: .25
Group 3: null
Group 0: .243
Group 1: null
Group 2: null
Group 3: .243
Group 0: 0.1234
Group 1: 0.1234
Group 2: .1234
Group 3: null
Search WWH ::




Custom Search