Home > Article > Web Front-end > How to Capture Multiple Occurrences of a Group in JavaScript Regex?
Capturing Arbitrary Groups in JavaScript Regex
When using regular expressions to capture groups, it's important to understand the limitations imposed by certain patterns. While repeated capturing groups can be used to match multiple occurrences, only the last capture is retained in JavaScript.
Consider the following example:
"foo bar baz".match(/^(\s*\w+)+$/)
In this pattern, the capturing group (s*w ) is repeated using the quantifier. However, JavaScript's regular expression engine only captures the last occurrence, not the intermediate matches. As a result, the output is:
["foo bar baz", " baz"]
To retrieve all captured matches, consider the following strategies:
Split on Delimiters:
If possible, split the string on predefined delimiters rather than using a complex regular expression.
Exec Loop with Repeated Groups:
Create a pattern that captures the repeated group and then use an exec loop to iterate through the matches. Once the complete group is captured, split it on the inner delimiter.
Multilevel Matching:
Break down the problem into multiple stages by capturing the repeated group in one pattern and then using a subsequent pattern to extract individual matches.
Example:
To match and split the string
/<(\w+(;\w+)*)>/g
This pattern captures the entire repeated group in Group 1. Then, in the exec loop, split the captured string using the ; delimiter.
var text = "a;b;;g;h;i; ;j;k; "; var r = /<(\w+(;\w+)*)>/g; var match; while ((match = r.exec(text)) != null) { console.log(match[1].split(";")); }
Output:
["c", "d", "e", "f"] ["xx", "yy", "zz"]
The above is the detailed content of How to Capture Multiple Occurrences of a Group in JavaScript Regex?. For more information, please follow other related articles on the PHP Chinese website!