简体   繁体   中英

Regex captures the last word of match as a group

I have a simple a regex like so _(([a-zA-Z]|_)*) to match the words anything after underscore like so _price_range * _qty_val , the catpure words which I am looking for price_range, qty_val but for weird mistake there are three matching groups, the last one being the last words of the matching word which is e and l in my case. Can someone explain or let me what I am doing wrong here? I don't want the last matching group.

Please check the screenshot. 在此处输入图片说明

The unexpected capture group is group 2, which is the inner brackets ([a-zA-Z]|_) .

A simple fix would be to make that group non-capturing:

_((?:[a-zA-Z]|_)*)

[a-zA-Z]|_ can be simplified to [a-zA-Z_] , so your regex can just be this:

_([a-zA-Z_]*)

Try this ( example here )

_[^ *]*     or grouped     _([^ *]*)

 let s = "_price_range * _qty_val" let r = s.match(/_[^ *]*/g).slice(0).map(x=>x.substr(1)); console.log(r);

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