通常,当您执行诸如 '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/