Jin Kim
Jin Kim

Reputation: 17732

How do I negate an exact match in regex?

If the user enters exactly "null", I want the regex match to fail. Entering "xxxnullxxx" is ok however.

The following regex rejects "null" but it also rejects any string containing "null", which I don't want.

^(?!.*null).*$

Upvotes: 4

Views: 2287

Answers (2)

Bohemian
Bohemian

Reputation: 425043

Add $ and remove .* from the look ahead:

^(?!null$).*

The trailing $ isn't needed.

Upvotes: 4

Martin Cup
Martin Cup

Reputation: 2582

This will match everything except for null: ^(?!(?:null)$).*$ I got the idea from here.

Upvotes: 1

Related Questions