Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand "Capturing groups" in regex with Java

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.

like image 853
Rollerball Avatar asked Apr 16 '13 13:04

Rollerball


1 Answers

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.

like image 132
Sergey Kalinichenko Avatar answered Sep 18 '22 17:09

Sergey Kalinichenko