繁体   English   中英

JS RegExp捕获括号

[英]JS RegExp capturing parentheses

我是JS RegExp的新手。 我对以下RegExp比赛感到困惑。

var x = "red apple"

var y = x.match(/red|green/i)

现在y["red"]

但是,如果我在redgreen周围添加一对括号,并使y为

var y = x.match(/(red|green)/i)

现在, y将变为["red", "red"] . 我在线搜索了https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp ,发现它叫做

For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9. For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

但是我不明白recalled from the resulting array's element or from predefined RegExp object's properties含义是什么? 谁能解释一下? 谢谢!

这意味着可以通过参考特定的组号[1] .. [n]来访问匹配结果( 捕获组 获取 ),其中n表示要访问的捕获组的编号。

注意: [0]适用于整体比赛结果。

var r = 'red apple'.match(/(red|green) apple/i);
if (r)
    console.log(r[0]); //=> "red apple"        # entire overall match
    console.log(r[1]); //=> "red"              # match result from 1st capture group

当将匹配结果存储到y (在这种情况下), y[0]始终是整体匹配 ,而y[1] .. y[9]包含各个捕获组。

/(red|green) apple/ ,应用于"This is a red apple." y将是["red apple", "red"]

用这个

var y = x.match(/(red|green)/gi);

答案是

y = ["red"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM