MaikoID
MaikoID

Reputation: 5007

How to capture group with regex Javascript?

greetings for all you Jedi that can properly work with JS, I unfortunately cannot.

I want to iterate in all matches of the respective string ' m10 m20 m30 xm40', except the xm40, and extract the numbers, 10, 20, 30:

'  m10 m20 m30 xm40'.match(/\s+m(\d+)/g)

but this is what I get in chrome console:

'  m10 m20 m30 xm40'.match(/\s+m(\d+)/g)
(3) ["  m10", " m20", " m30"]

why is the 'm' being captured too? I just can't understand. I've tried a lot of combination without success. Any thoughts?

Bye!

Upvotes: 1

Views: 50

Answers (2)

Andy
Andy

Reputation: 63579

Another way of getting just those digits would be to match against /\sm\d+/g first, and then return the results of mapping over those results and extracting the digits.

var m = str.match(/\sm\d+/g).map(el => el.match(/\d+/)[0]);

DEMO

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Use RegExp.exec() function:

const regex = /\sm(\d+)/g;
const str = '  m10 m20 m30 xm40';
let result = [];

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }        
    result.push(+m[1]);
}

console.log(result);

Upvotes: 2

Related Questions