Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude exact strings (not substrings) from matches in regex?

Tags:

regex

I've found lots of questions on here on how to exclude a substring from results, but I want to exclude lines that are exact matches and simply can't figure out how to do it.

With the test data below, how would I match everything except for 11 and 111?

0
1
00
01
10
11
000
001
010
011
100
101
110
111
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010

I've tried various things, such as this:

^((?!11|111).)*$

But that excludes substring matches, when again I'm wanting to exclude exact matches.

Is this possible with regex? If so, how can excluding exact matches be achieved?

like image 308
Nate Avatar asked Sep 20 '14 15:09

Nate


2 Answers

You need to have the end-of-line included in the negative look ahead:

^(?!(11|111)$).*$

See live demo (using your data)

Without including the end-of-line, you are only asserting that the input doesn't start with 11 or 111, when what you want is to assert is that the entire input (start to end) isn't 11 or 111.

like image 53
Bohemian Avatar answered Sep 22 '22 12:09

Bohemian


Through PCRE verb (*SKIP)(*F),

^(?:11|111)$(*SKIP)(*F)|.+

DEMO

OR

^(?:(?!^(?:111|11)$).)++$

DEMO

like image 25
Avinash Raj Avatar answered Sep 22 '22 12:09

Avinash Raj