使用 JavaScript 正则表达式的全局匹配 [英] Global Matches using JavaScript Regular Expressions

查看:56
本文介绍了使用 JavaScript 正则表达式的全局匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

如果未设置全局标志 (g),则数组的元素 0 包含整个匹配项,而元素 1 到 n 包含任何子匹配项.此行为与未设置全局标志时 exec 方法(正则表达式)(JavaScript)的行为相同.如果设置了全局标志,则元素 0 到 n 包含发生的所有匹配项.

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

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

示例:

<代码>>s = "Foo Bar"福吧">s.match(/([A-Z])([a-z]+)/)["Foo", "F", "oo"]>s.match(/([A-Z])([a-z]+)/g)[Foo",酒吧"]

没有像 python findall 那样从所有匹配中收集所有组的内置函数,但是使用 exec 很容易编写:

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

结果:

<预><代码>[数组[3]0:福"1:F"2:哦"指数:0输入:Foo Bar"长度:3__proto__:数组[0],数组[3]0:酒吧"1:乙"2:阿"指数:4输入:Foo Bar"长度:3__proto__:数组[0]]

Usually when you do something like 'test'.match(/(e)/) you would receive an array ['e', 'e'], where the first element is the match itself and the second from the selector (braces), but when using the global modifier as in 'test'.match(/(e)/g) it will omit the match, while it doesn't in case I don't use selectors at all.

I wonder if and where the following behavior is specified (using Chromium for this test).

解决方案

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

In other words, when g is provided, match collects only topmost matches, ignoring any capturing groups.

Example:

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

There's no built-in that would collect all groups from all matches, like python findall does, but it's easy to write using 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")

Result:

[
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 正则表达式的全局匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆