Home > Back-end >  Regex negative lookahead not matching last space
Regex negative lookahead not matching last space

Time:03-18

I have text:

test: [ABCD]
test: foobar
test:      [ABCD]

And I've wrote this regex:

test:\s (?!\[ABCD)

So basicaly I want to find any occurence where test: is NOT followed by [ABCD and there can be any amount of whitespace between the two.

So for the first two examples it works as intended but I have problem with the third one: it looks like because of this part: (?!\[ABCD) the \s is not matching last space if there are more than one. Why is that and how to solve it? I want to third example bahave just like frist one. Screenshot from regex101 to illustrate the issue:

Failing regex

CodePudding user response:

You have one good answer to match the entire line if it follows the criteria, but based on this:

I want to find any occurence where "test:" is NOT followed by "[ABCD" and there can be any amount of whitespace between the two.

If you want to only match the "test:" part, you can just move the whitespace character into the negative look-ahead on what you have.

test:(?!\s \[ABCD)

Screenshot from regex101 using your example phrases:

example of working regex

CodePudding user response:

You need the lookahead before the match with an anchor:

/^(?!test:\s \[ABCD\]).*/

Demo

  • Related