Danpe
Danpe

Reputation: 19047

Regex match if word doesn't appear before other word

I have this Regex (Live):

^((?!when|how|where).*?(ARE|WANNA|DO).*\?)$

And these three sentences:

Hey are we out after the rain?
Where are we meeting?
Dan where are we gonna meet?

My regex matches 1 and 3, but should match only 1.

My base rule is that one of the words when|how|where can not appear before one of the words ARE|WANNA|DO.

Any ideas?

Upvotes: 2

Views: 285

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208555

The following should work:

^((?!when|how|where).)*?(ARE|WANNA|DO).*\?$

Putting the negative lookahead inside a repeating group like ((?!foo).)* causes the lookahead to be checked before each character is matched, so this would match any number of any character but stop if foo were encountered.

Example: http://rubular.com/r/0cw8eaFMXB

Upvotes: 3

Jerry
Jerry

Reputation: 71578

Try using this instead:

^((?:(?!when|how|where).)*?(ARE|WANNA|DO).*\?)$
  ^^^                   ^

This group will 'check' each . before matching it and make sure that each dot doesn't have a when|how|where ahead.

Upvotes: 1

Related Questions