Regex captures the last word of match as a group

Viewed 209

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. enter image description here

2 Answers

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);

Related