简体   繁体   English

JS RegExp捕获括号

[英]JS RegExp capturing parentheses

I am a newbie to JS RegExp. 我是JS RegExp的新手。 I got confused by the following RegExp matches. 我对以下RegExp比赛感到困惑。

var x = "red apple"

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

Now y is ["red"] . 现在y["red"]

However if I add a pair of parentheses around red and green and make y to be 但是,如果我在redgreen周围添加一对括号,并使y为

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

Now, y would become ["red", "red"] . 现在, y将变为["red", "red"] I have searched online https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp and found that it's something called capturing parentheses . 我在线搜索了https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp ,发现它叫做捕获括号

It says 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. 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.

But I don't understand what does it mean by recalled from the resulting array's element or from predefined RegExp object's properties ? 但是我不明白recalled from the resulting array's element or from predefined RegExp object's properties含义是什么? Can anyone please explain ? 谁能解释一下? Thank you! 谢谢!

It means that the match result ( obtained from the capturing group ) can be accessed by referring to that specific group number [1] .. [n] where n represents the number of the capturing group you want to access. 这意味着可以通过参考特定的组号[1] .. [n]来访问匹配结果( 捕获组 获取 ),其中n表示要访问的捕获组的编号。

Note: [0] applies to the overall match result. 注意: [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

When the match result is stored to (in this case) y , y[0] is always the overall match , while y[1] .. y[9] contain the individual capturing groups. 当将匹配结果存储到y (在这种情况下), y[0]始终是整体匹配 ,而y[1] .. y[9]包含各个捕获组。

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

Use this 用这个

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

Answer is 答案是

y = ["red"]

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

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