Nate
Nate

Reputation: 28354

How to exclude exact strings (not substrings) from matches in 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?

Upvotes: 7

Views: 4453

Answers (2)

Bohemian
Bohemian

Reputation: 424983

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.

Upvotes: 9

Avinash Raj
Avinash Raj

Reputation: 174696

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

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

DEMO

OR

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

DEMO

Upvotes: 1

Related Questions