I am studying for the java OCP and at the moment I am stuck at understanding the "Capturing groups" section. It is a way too abstract as a description. Could you please (if you have time) give me some real examples using "Capturing groups"?
Is anybody able to provide me with a concrete example of the following statement?
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g". The portion of the input string that matches the capturing group will be saved in memory for later recall via backreferences (as discussed below in the section, Backreferences).
I am pretty sure I'll get it as soon as I see a concrete example.
Thanks in advance.
Among other things, regex lets you obtain portions of the input that were matched by various parts of the regular expression. Sometimes you need the entire match, but often you need only a part of it. For example, this regular expression matches "Page X of Y"
strings:
Page \d+ of \d+
If you pass it a string
Page 14 of 203
you will match the entire string. Now let's say that you want only 14
and 203
. No problem - regex library lets you enclose the two \d+
in parentheses, and then retrieve only the "14"
and "203"
strings from the match.
Page (\d+) of (\d+)
The above expression creates two capturing groups. The Matcher
object obtained by matching the pattern lets you retrieve the content of these groups individually:
Pattern p = Pattern.compile("Page (\\d+) of (\\d+)");
String text = "Page 14 of 203";
Matcher m = p.matcher(text);
if (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
}
This prints 14
and 203
.
Demo on ideone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With