Using group numbers with Macher
The whole pattern is defined to be group number 0.
Any capturing group in the pattern start indexing from 1.
The indices are defined by the order of the opening parentheses of the capturing groups.
EXAMPLE
Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
String: "!* UserName10 John Smith 01123 *!"
group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):
group(3): John Smith
group(4):
group(5): 01123
There are 5 groups which are each enclosed in parentheses.
group(0) gives you the entire matched string.
groups 2 and 4 are simply the white space (space char / line feed / tab)
CODE
Pattern pattern=Pattern.compile("pattern");
Macher matcher=pattern.matcher("string");
if(matcher.matches()) {
grp0 = matcher.group(0);
grp1 = matcher.group(1);
...
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.