簡體   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