javascript - 我无法准确理解 JavaScript 的方法 string.match(regexp) 的 g 标志是如何工作的

标签 javascript regex string match gflags

在《JavaScript: The Good Parts》一书中解释了方法string.match(regexp)如下:

The match method matches a string and a regular expression. How it does this depends on the g flag. If there is no g flag, then the result of calling string .match( regexp ) is the same as calling regexp .exec( string ). However, if the regexp has the g flag, then it produces an array of all the matches but excludes the capturing groups:

然后书中给出了代码示例:

var text = '<html><body bgcolor=linen><p>This is <b>bold<\/b>!<\/p><\/body><\/html>';
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;
a = text.match(tags);
for (i = 0; i < a.length; i += 1) {
    document.writeln(('// [' + i + '] ' + a[i]).entityify());
}
// The result is
// [0] <html>
// [1] <body bgcolor=linen>
// [2] <p>
// [3] This is
// [4] <b>
// [5] bold
// [6] </b>
// [7] !
// [8] </p>
// [9] </body>
// [10] </html>

我的问题是我无法理解“但不包括捕获组”。

在上面的代码示例中,html</html>在捕获组中。为什么它仍然包含在结果数组中?

/</html>也在捕获组中。为什么它包含在结果数组中?

你能用上面的代码示例解释“但不包括捕获组”吗?

非常感谢!

最佳答案

In the code example above, html in the is in a capturing group. And why is it still included in the result array?

因为它是完全匹配的。当他说“但不包括捕获组”时,他并不是说从完整匹配结果来看,只是捕获组的内容没有在数组中重申。如果包含捕获组,您会看到

// The result is
// [0] <html>
// [1]           // From the capture group; nothing here
// [2] html      // From the capture group
// [3]           // From the capture group; nothing here
// ...

And / in the is also in a capturing group. And why is it included in the result array?

同上原因:它是整体匹配的一部分,这就是结果中的内容;各个捕获组的内容不是。

用一个更简单的例子就更容易理解了。考虑这段代码:

var s = "test1 test2";
var re = /(test)(.)/g;
var r = s.match(re);
var i;
for (i = 0; i < r.length; ++i) {
    console.log("[" + i + "]: '" + r[i] + "'");
}

因为正则表达式有g标志,数组中只包含全匹配,所以我们看到:

[0]: 'test1'
[1]: 'test2'

在每种情况下,数组中的条目都是完整匹配项,其中包括在构成整个表达式的捕获组中匹配的字符。

如果我们删除 g 标志但不更改任何其他内容,我们将获得第一个完整匹配项,然后是两个捕获组的内容:

[0]: 'test1'    // The full match, including the stuff from each capture group
[1]: 'test'     // Capture group 0's contents
[2]: '1'        // Capture group 1's contents

在那里,第一个条目是完全匹配;然后第二个和第三个是捕获组的内容。注意捕获组的内容

关于javascript - 我无法准确理解 JavaScript 的方法 string.match(regexp) 的 g 标志是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901334/

相关文章:

regex - 在Pig中使用正则表达式解析日志文件

java - 计算创建的字符串对象的数量

javascript - Angular 1.5 嵌套组件绑定(bind)父值

javascript - Redux mapStateToProps 属性依赖

javascript - 每次点击时显示一些额外的 div

javascript - 使用 JavaScript 转换 ISO 8601 持续时间

Python RegEx 以给定单词开头的整行

javascript - 从 GMail URL 获取唯一电子邮件标识符

c# - 为什么 "string"被认为是 "String"的简化版本?

string - Python3 TypeError : list indices must be integers or slices, 不是 str