javascript - 使用 JavaScript 正则表达式进行全局匹配

标签 javascript regex

通常,当您执行诸如 'test'.match(/(e)/) 之类的操作时,您会收到一个数组 ['e', 'e'],其中第一个元素是匹配本身,第二个元素是选择器(大括号),但是当使用 'test'.match(/(e)/g) 中的全局修饰符时,它将省略匹配,但如果我根本不使用选择器则不匹配。

我想知道是否以及在何处指定了以下行为(使用 Chromium 进行此测试)。

最佳答案

If the global flag (g) is not set, Element zero of the array contains the entire match, while elements 1 through n contain any submatches. This behavior is the same as the behavior of the exec Method (Regular Expression) (JavaScript) when the global flag is not set. If the global flag is set, elements 0 through n contain all matches that occurred.

http://msdn.microsoft.com/en-us/library/ie/7df7sf4x(v=vs.94).aspx

换句话说,当提供 g 时,match 仅收集最上面的匹配项,忽略任何捕获组。

示例:

> s = "Foo Bar"
"Foo Bar"
> s.match(/([A-Z])([a-z]+)/)
["Foo", "F", "oo"]
> s.match(/([A-Z])([a-z]+)/g)
["Foo", "Bar"]

没有内置函数可以像 python findall 那样收集所有匹配项中的所有组,但使用 exec 可以轻松编写:

function matchAll(re, str) {
    var p, r = [];
    while(p = re.exec(str))
        r.push(p);
    return r;
}
matchAll(/([A-Z])([a-z]+)/g, "Foo Bar")

结果:

[
Array[3]
0: "Foo"
1: "F"
2: "oo"
index: 0
input: "Foo Bar"
length: 3
__proto__: Array[0]
, 
Array[3]
0: "Bar"
1: "B"
2: "ar"
index: 4
input: "Foo Bar"
length: 3
__proto__: Array[0]
]

关于javascript - 使用 JavaScript 正则表达式进行全局匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14457386/

相关文章:

javascript - Three.JS => 加载大约 300 Mb 的大 .Obj 文件会使浏览器崩溃并需要很长时间才能加载

javascript - 如何仅使用 javascript 更改按钮颜色 onclick?

javascript - 使用正则表达式验证输入中是否包含任何非数字

python - 使用 re.sub 替换不同大小的小数时对齐小数位

regex - grep - 显示匹配行的两部分

java - regex\\p{So} 不过滤 BLACK CIRCLE FOR RECORD

javascript - 逐一淡入div内容

javascript - 使用javascript的乐透号码随机生成器

javascript - DevExpress/至尊dxSelectBox

java - 正则表达式replaceAll不适用于速度模板