Home > Web Front-end > JS Tutorial > How to Capture Multiple Occurrences of a Group in JavaScript Regex?

How to Capture Multiple Occurrences of a Group in JavaScript Regex?

Mary-Kate Olsen
Release: 2024-11-11 03:16:03
Original
452 people have browsed it

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+)+$/)
Copy after login

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"]
Copy after login

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 , use the following pattern:

/<(\w+(;\w+)*)>/g
Copy after login

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(";"));
}
Copy after login

Output:

["c", "d", "e", "f"]
["xx", "yy", "zz"]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template