简体   繁体   中英

Regex…non capturing group still capturing - javascript?

Probably due to a misunderstanding of my own, but would like to confirm..

var match = '4 bedroom house'.match( /(?:\\d+ bedroom)(.*)/i);

As I understand it ?: should mean that while the group is used for matching, it shoudn't be returned in the results?

However when I console log match I get:

["4 bedroom house", " house", index: 0, input: "4 bedroom house"]

I am not interested in match[0] how can I exclude it?

(?:..) called non-capturing group which does the matching operation only. match function in-turn return all the matched characters. In-order to return only the captured characters, you need to call exec function.

> /(?:\d+ bedroom)(.*)/i.exec('4 bedroom house')[1]
' house'
> /(?:\d+ bedroom\b)\s*(.*)/i.exec('4 bedroom house')[1]
'house'

[1] at the last helps to print all the characters which are captured by the group index 1.

match works the same as exec when the g flag is omitted. The first value in the matches array is the complete match so I don't think you can omit the first array value when using match or exec.

workaround to omit first value:

var match = ('4 bedroom house'.match( /(?:\d+ bedroom)(.*)/i)||[]).slice(1); // [" house"]

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