[英]JS RegExp capturing parentheses
我是JS RegExp的新手。 我对以下RegExp比赛感到困惑。
var x = "red apple"
var y = x.match(/red|green/i)
现在y
是["red"]
。
但是,如果我在red
和green
周围添加一对括号,并使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
含义是什么? 谁能解释一下? 谢谢!
当将匹配结果存储到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.