COMisHARD
COMisHARD

Reputation: 925

How to negate a string in regex

I know three things...

1) I know that:

a.{1,250}?z

Will check that a is within 250 characters of z.

2) I know that

a[^b]{1,250}?z

Will check that a is within 250 characters of z, but that none of those characters are b.

3) I also know that

a[^bad]{1,250}?z

Will check that a is within 250 characters of z, but that none of those characters are b, a, or d.

but

4)

How wow would I check that a occurs within 250 characters of z, but that the word bad does not appear between them?

Imagining "string" required an exact match (like in a google search) the pseudo-code would look like:

a[^"bad"]{1,250}?z

Upvotes: 2

Views: 1693

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Simple, use a negative lookahead.

a(?:(?!bad).){1,250}?z

(?:(?!bad).) would match any character (except line breaks) but not of the substring bad.

DEMO

And also you must use anchors or word boundaries in-order to do an exact match or otherwise, the above regex would match adccz for this acbadccz input.

\ba(?:(?!bad).){1,250}?z\b

Upvotes: 6

Related Questions