Discussion on JavaScript regular expression grouping matching
- 2020-05-27 04:12:15
- OfStack
grammar
Metacharacter: (pattern) function: used for groups that are repeatedly matched
Properties $1 to $9, if they exist, are used to get the substring matched in the corresponding group
\1 or $1 is used to match the contents of the first group
\2 or $2 is used to match the contents of the first group
...
\9 or $9 is used to match the contents of the first group
Usage examples
var reg = /(A+)((B|C|D)+)(E+)/gi;// The regular expression has 4 A grouping
// Corresponding relations between
//RegExp.$1 <-> (A+)
//RegExp.$2 <-> ((B|C|D)+)
//RegExp.$3 <-> (B|C|D)
//RegExp.$4 <-> (E+)
The above code also shows the usage of $1~$9
$1~$9 are static properties predefined by the regular expression, referenced by RegExp.$1
Grouping nested relationship description
The code above also illustrates the nesting of groups
// The test environment Chrome The browser
var str = "ABCDE";
var reg = /(A+)((B|C|D)+)(E+)/gi;
str.match(reg);// Output: ["ABCDE"]
reg.exec(str,'i');// Output: ["ABCDE", "A", "BCD", "D", "E"]
RegExp.$1;// Output: "A"
RegExp.$2;// Output: "BCD"
RegExp.$3;// Output: "D"
RegExp.$4;// Output: "E"
This makes it easy to see the nesting of groups
To sum up: when there is a small group in a large group, the small group is the group next to the large group, and so on
That's all for this article, I hope you enjoy it.