简体   繁体   中英

JS RegExp capturing parentheses

I am a newbie to JS RegExp. I got confused by the following RegExp matches.

var x = "red apple"

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

Now y is ["red"] .

However if I add a pair of parentheses around red and green and make y to be

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

Now, y would become ["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 .

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.

But I don't understand what does it mean by 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.

Note: [0] applies to the overall match result.

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.

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

Use this

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

Answer is

y = ["red"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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