Mateusz Marchel
Mateusz Marchel

Reputation: 932

Regex negative lookahead not matching last space

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

Upvotes: 0

Views: 147

Answers (3)

The fourth bird
The fourth bird

Reputation: 163277

You get the last match, as \s+ can backtrack one step to make sure the last assertion is true.

There is no language listed, but is possessive quantifiers are supported, you can also use

test:\s++(?!\[ABCD)

See a regex demo.

Upvotes: 1

Jacob K
Jacob K

Reputation: 1183

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

Upvotes: 1

dawg
dawg

Reputation: 103814

You need the lookahead before the match with an anchor:

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

Demo

Upvotes: 1

Related Questions