[英]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.