There are two types of capture groups:One is a common capturing group. If there is no ambiguity, it is referred to as a capturing group. syntax rules: (expression); the other is a naming capturing group. syntax rules :(? <Name> expression) or (? 'Name' expression). The two statements are equivalent.
1. Numbering rulesIf you do not explicitly name a capture group, that is, you do not use a named capture group, you must access all capture groups in numerical order, the number of the capture group is in the order that "(" appears, from left to right (\ d {4})-(\ d {2}-(\ d )) 1 1 2 3 3 2 the regular expression above can be used to match a date in the format of yyyy-MM-dd. In order to be distinguished in the following table, there is also a group with a default number of 0 in the \ d {2} And \ d, which indicates that the regular expression matches the string with the above regular expression as a whole: matched results:
| No. |
Name |
Capture Group |
Matching content |
| 0 |
|
(\ D {4})-(\ d {2}-(\ d )) |
2008-12-31 |
| 1 |
|
(\ D {4 }) |
2008 |
| 2 |
|
(\ D {2}-(\ d )) |
12-31 |
| 3 |
|
(\ D) |
31 |
If a group is explicitly named, that is, a capture group, the captured content can be referenced by the group name. However, if a regular expression uses both normal capture groups, if a capturing group is also used, pay special attention to the number of the capturing group. The numbering rule is to first number a common capturing group, then the name of the capture group is numbered (\ d {4 })-(? <Date> \ d {2}-(\ d) 1 1 3 2 23 use the above regular expression to match the string: match result:
| No. |
Name |
Capture Group |
Matching content |
| 0 |
|
(\ D {4})-(\ d {2}-(\ d )) |
2008-12-31 |
| 1 |
|
(\ D {4 }) |
2008 |
| 2 |
|
(\ D) |
31 |
| 3 |
Date |
(? <Date> \ d {2}-(\ d )) |
12-31 |
2. Capture group referencesThe following types of regular expressions are generally used to reference the content captured by the previous capturing group, which is called reverse reference B. In a regular expression ,(? (Expression) true | false) condition expression c) in the program, the reference to the capture content of the capture group is reversed reference to the reference of the normal capture group, the syntax rule is: \ k <num>, usually abbreviated as \ num, where num is a decimal number, that is, the number of the capture group references to the name capture group. The syntax rule is as follows: \ k <name> or \ k'name'