Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning matched lookahead groups

Good day,

I am trying to return groups of 3 digits of a given string where digits are "consumed" twice in JavaScript:

From a string "123 456" I would like exec to return ["1", "12"] for the first match, ["2", "23"] and so on.

I tried using a lookahead like this:

let exp = /(\d(?=\d\d))/g;    
let match;

while(match = exp.exec("1234 454")) {
    console.log(match);
}

This, will however still only each digit which precedes two digits.

Does someone have a solution? I have searched but am not exactly sure what to search for so I might have missed something.

Thank you in advance!

like image 465
Sebastian Avatar asked Feb 06 '26 12:02

Sebastian


1 Answers

You need to capture inside a positive lookahead here:

let exp = /(?=((\d)\d))/g;    
let match;
while(match = exp.exec("1234 454")) {
     if (match.index === exp.lastIndex) { // \ 
        exp.lastIndex++;                  // - Prevent infinite loop
    }                                     // /
    console.log([match[1], match[2]]);    // Print the output
}

The (?=((\d)\d)) pattern matches a location followed with 2 digits (captured into Group 1) the first being captured into Group 2.

like image 193
Wiktor Stribiżew Avatar answered Feb 09 '26 02:02

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!