Easy Tutorial
❮ Builder Pattern 2 Linux Useful Command ❯

English: ## Java Regular Expression Capture Groups

Category Programming Techniques

Capture groups are divided into:

Ordinary Capture Groups

Starting from the left side of the regular expression, each appearance of a left parenthesis "(" is considered a group, with group numbering starting from 1. 0 represents the entire expression.

For the date string: 2017-04-25, the expression is as follows

(\\d{4})-((\\d{2})-(\\d{2}))

There are 4 left parentheses, so there are 4 groups:

Number Capture Group Match
0 (\d{4})-((\d{2})-(\d{2})) 2017-04-25
1 (\d{4}) 2017
2 ((\d{2})-(\d{2})) 04-25
3 (\d{2}) 04
4 (\d{2}) 25
public static final String DATE_STRING = "2017-04-25";
public static final String P_COMM = "(\\d{4})-((\\d{2})-(\\d{2}))";

Pattern pattern = Pattern.compile(P_COMM);
Matcher matcher = pattern.matcher(DATE_STRING);
matcher.find();//this line is necessary
System.out.printf("\nmatcher.group(0) value:%s", matcher.group(0));
System.out.printf("\nmatcher.group(1) value:%s", matcher.group(1));
System.out.printf("\nmatcher.group(2) value:%s", matcher.group(2));
System.out.printf("\nmatcher.group(3) value:%s", matcher.group(3));
System.out.printf("\nmatcher.group(4) value:%s", matcher.group(4));

Named Capture Groups

Each capture group that starts with a left parenthesis is immediately followed by ?, and then the regular expression.

For the date string: 2017-04-25, the expression is as follows:

(?<year>\\d{4})-(?<md>(?<month>\\d{2})-(?<date>\\d{2}))

There are 4 named capture groups, respectively:

Number Name Capture Group Match
0 0 (?\d{4})-(?(?\d{2})-(?\d{2})) 2017-04-25
1 year (?\d{4})- 2017
2 md (?(?\d{2})-(?\d{2})) 04-25
3 month (?\d{2}) 04
4 date (?\d{2}) 25

Named capture groups can also be accessed using their numbers.

``` public static final String P_NAMED = "(?<year>\d{4})-(?<md>(?<month>\d{2})-(?<date>\d{2}))"; public static final String DATE_STRING = "2017-04-25";

Pattern pattern = Pattern.compile(P_NAMED); Matcher matcher = pattern.matcher(DATE_STRING); matcher.find(); System.out.printf("\n===========Retrieve by Name============="); System.out.printf("\nmatcher.group(0) value:%s", matcher.group(0)); System.out.printf("\n matcher.group('year') value:%s", matcher.group("year")); System.out.printf("\nmatcher.group('md') value:%s", matcher.group("md")); System.out.printf("\nmatcher.group('month') value:%s", matcher.group("month")); System.out.printf("\nmatcher.group('date') value:%s", matcher.group("date")); matcher.reset(); System.out.printf("\n===========Retrieve by Number============="); matcher.find(); System.out.printf("\nmatcher.group(0) value:%s", matcher.group(0)); System.out.printf("\nmatcher.group(1) value:%s", matcher.group(1)); System.out.printf("\nmatcher.group(2) value:%s", matcher.group(2)); System.out.printf("\nmatcher.group(3) value:%s", matcher.group(3)); System.out

❮ Builder Pattern 2 Linux Useful Command ❯