Trying to understand "Group Capture" in regex with Java

I am learning JCP OCP, and at the moment I am stuck in understanding the section "Capturing groups" . It is too abstract as a description. Could you (if you have the time) give me some real examples using "Capturing groups"?

Can anyone provide me with a concrete example of the following statement?

Capturing groups is a way of processing multiple characters as a single block. They are created by placing characters to group within a set of parentheses. For example, a regular expression (dog) creates one group containing the letters "d" "o" and "g". the part of the input line that corresponds to the capture group will be stored in memory for later recall via backlinks (as discussed below in the section “Backlinks”).

I am sure that I will receive it as soon as I see a concrete example.

Thanks in advance.

+5
source share
5 answers

, , . , . , "Page X of Y":

Page \d+ of \d+

Page 14 of 203

. , 14 203. - \d+ , "14" "203" .

Page (\d+) of (\d+)

. Matcher, , :

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));
}

14 203.

.

+13

Matcher, , ​​ , . :

String dateStr = "1981-06-25";

Pattern datePatt = Pattern.compile("([0-9]{4})/([0-9]{2})/([0-9]{2})");
...
Matcher m = datePatt.matcher(dateStr);
if (m.matches()) {
    int year  = Integer.parseInt(m.group(1));
    int month = Integer.parseInt(m.group(2));
    int day   = Integer.parseInt(m.group(3));
}

, 1, 2 3 .

+2

. ,

/^(http|ftp).*/

, , http ftp.

+1

,

cat (dog )?bus

cat dog bus cat bus. , dog - ?. , .

James while John (had )+a better effect on the teacher

James while John had had had had had had had had had had had a better effect on the teacher

had.

(, ).

(cat|dog) is a \1

\1 - , . dog is a dog cat is a cat, dog is a cat .

0

, .

, (), . , . , , , , , .

0
source

All Articles