Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading