Home  >  Article  >  Web Front-end  >  How to Capture Multiple Groups in JavaScript Regular Expressions?

How to Capture Multiple Groups in JavaScript Regular Expressions?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 08:30:031010browse

How to Capture Multiple Groups in JavaScript Regular Expressions?

Access All Captures in JavaScript Regular Expressions

The problem arises when trying to capture multiple groups in a JavaScript regular expression, where only the last capture is retained.

Consider the following example:

"foo bar baz".match(/^(\s*\w+)+$/)

Instead of returning all matches like ["foo", "bar", "baz"], it only returns ["baz"]. This behavior occurs because repeated capturing groups overwrite previous captures.

To resolve this, consider alternative approaches:

  • Split on Delimiters: If possible, split the string on a known delimiter instead of using a repeated capturing group.
  • Regex with g Flag: Use a regular expression with the g flag to iterate over all matches. Note that this may not be an exact equivalent to repeated capturing groups.
  • Multilevel Matching: Perform multiple regex matches to capture specific patterns and then further split or process them.

For instance, to capture a sequence of words enclosed in < > and split them on ;, consider the following example:

var text = "a;b;<c;d;e;f>;g;h;i;<no no no>;j;k;<xx;yy;zz>";

var r = /<(\w+(;\w+)*)>/g;

var match;
while ((match = r.exec(text)) != null) {
  print(match[1].split(";"));
}

This regex splits the captured sequence into individual words.

References:

  • [Regular Expressions Information: Repeating vs Capturing Groups](https://www.regular-expressions.info/repeating-a-capturing-group-vs-capturing-a-repeating-group)

The above is the detailed content of How to Capture Multiple Groups in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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