How can I write a regular expression to match both numbers? A simple character expression cannot be completed. in this case, we can define a character set combination (character class) for matching. This is the group match.
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
Var reg =/(A +) (B | C | D) +) (E +)/gi; // This regular expression has four groups // ing relations // 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.
// 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: "A" 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.
The above is all the content of this article. I hope you will like it.