首页 > web前端 > js教程 > 正文

如何在重复的 JavaScript 正则表达式中捕获多个组?

Linda Hamilton
发布: 2024-11-13 10:33:02
原创
540 人浏览过

How to Capture Multiple Groups in a Repeated JavaScript Regex?

Capturing Arbitrary Groups in JavaScript Regexp

When using capturing groups in JavaScript regular expressions, it's essential to understand the limitations. By default, only the last capture of a repeated group is kept, even if the group is nested.

Example: Nested Capture Group

Consider the following regular expression:

/^(\s*\w+)+$/
登录后复制

Expected output:

["foo bar baz", "foo", " bar", " baz"]
登录后复制

Actual output:

["foo bar baz", " baz"]
登录后复制

In this case, only the last captured group, " baz", is returned. This is because JavaScript only retains the final capture for each repeated group.

Options for Capturing Multiple Groups

To overcome this limitation, several options are available:

  • Split on Delimiters: If possible, use string splitting to separate the desired segments.
  • Exec Loop and Splitting: Use an exec loop to repeatedly match the pattern within a string and split the captured group into individual matches.
  • Multilevel Matching: Capture the repeated group in one match and then use another regex to extract the individual segments.

Example: Exec Loop and Splitting

Here's an example using an exec loop to capture and split a nested group:

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

// Output:
// ["c", "d", "e", "f"]
// ["xx", "yy", "zz"]
登录后复制

In this example, the nested group is captured as group 1, which is then split on the semicolon delimiter.

Related Questions

  • How do you access the matched groups in a JavaScript regex?

以上是如何在重复的 JavaScript 正则表达式中捕获多个组?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板