Discussion on JavaScript regular expression group matching
Syntax
Metacharacters (pattern): used for group matching repeatedly
Attribute $1 ~ $9 if it exists, it is used to obtain the matched substring in the corresponding group.
\ 1 or $1 is used to match the content in the first group.
\ 2 or $2 is used to match the content in the first group.
...
\ 9 or $9 is used to match the content in the first group.
Usage example
1 2 3 4 5 6 |
Var reg =/(A +) (B | C | D) +) (E +)/gi; // This regular expression has four groups. // Ing // RegExp. $1 <-> (A +) // RegExp. $2 <-> (B | C | D) +) // RegExp. $3 <-> (B | C | D) // RegExp. $4 <-> (E +) |
The above code also provides $1 ~ $9 usage
$1 ~ $9 is a pre-defined static attribute of a regular expression, which is referenced by RegExp. $1.
Group nesting relationship description
The code above can also describe the nesting relationship of groups.
1 2 3 4 5 6 7 8 9 |
// Test environment: Chrome browser Var str = "ABCDE "; Var reg =/(A +) (B | C | D) +) (E +)/gi; Str. match (reg); // output: ["ABCDE"] Reg.exe c (str, 'I'); // output: ["ABCDE", "A", "BCD", "D", "E"] RegExp. $1; // output: "" RegExp. $2; // output: "BCD" RegExp. $3; // output: "D" RegExp. $4; // output: "E" |
In this way, we can clearly see the nested relationship of the group.
To sum up, when a large group contains a small group, a small group is the group that is placed after the large group, and so on.