Java Reference
In-Depth Information
substring
}
}
}
}
TryCapturingGroups.java
This produces the following 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
How It Works
The regular expression here defines four capturing groups:
• Group 0: The whole expression
• Group 1: The subexpression "(\\d+(\\.\\d*)?)"
• Group 2: The subexpression "(\\.\\d*)"
• Group 3: The subexpression "(\\.\\d+)"
After each successful call of the find() method for m , you output the text captured by each group by
passing the index value for the group to the group() method. Note that because you want to output group
0 as well as the other groups, you start the loop index from 0 and allow it to equal the value returned by
groupCount() so as to index over all the groups.
You can see from the output that group 1 corresponds to numbers beginning with a digit, and group 3
corresponds to numbers starting with a decimal point, so either one or the other of these is always null .
Group 2 corresponds to the sub-pattern within group 1 that matches the fractional part of a number that
Search WWH ::




Custom Search