Rehan
Rehan

Reputation: 4013

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

Upvotes: 3

Views: 303

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92477

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

Upvotes: 0

Sweeper
Sweeper

Reputation: 272000

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_]*)

Upvotes: 1

Related Questions