Home > Enterprise >  javascript regex lookahead why abc match?
javascript regex lookahead why abc match?

Time:10-14

Input text is:

test 
abc abc

I want to get all text before abc with

. (?=abc)

https://regex101.com/r/4XiJ2r/1

why with 2 abc it matches the first one?

CodePudding user response:

Adding a ? (to make it . ?(?=abc)) to your quantifier will make it lazy, so it'll stop at the first ocurrence, but it will still find the other ocurrences and put them in different "groups": https://regex101.com/r/BjrowX/1

CodePudding user response:

The quantifier requires the match to be at least 1 character. In abc abc there's nothing before the first abc, so it can't be the match. So the match is everything before the second abc.

CodePudding user response:

You need to handle new lines, so you need m flag. You don't need global search, because you need to stop capturing before first abc appearance, so remove g flag. This is one of the multiple options:

const str = `test
abc abc`;

const result = str.match(/[\s\S]*?(?=abc)/m);

console.log(result);

  • Related