moonshot
moonshot

Reputation: 699

Combining Positive Lookahead and Negative Lookahead - Regex

I'm writing a simple regex in postgres 9.5 using ~

I want to combine a positive lookahead and a negative lookahead. This is my Regex which is not working:

CHANGE.+(?=SHOES.+(?!NIKE))

Here is my DEMO and below is an example of my issue:

MATCH:

CHANGE THE SHOES TO REBOOK.

NOT MATCH:

CHANGE OF SHOES TO NIKE AIRS.

Upvotes: 0

Views: 1057

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522386

Here is a solution which only uses a single negative lookahead:

SELECT *
FROM yourTable
WHERE col ~ 'CHANGE.+SHOES(?!.*NIKE)';

If you want an exact answer to your question, see the response by @trincot.

Upvotes: 1

trincot
trincot

Reputation: 350841

The .+ after SHOES is greedy and so the (?! will only be checked at the end of the string where it is true (i.e. there is no NIKE there), and so there is no backtracking.

Instead do this:

CHANGE.+(?=SHOES(?!.*NIKE))

Upvotes: 0

Related Questions