Florian Baierl
Florian Baierl

Reputation: 2491

Regex - more than one "does not contain"/"contains"

I need some regular expressions for "contain" and "do not contain". Normally I'd just write:

Contains : ((.*WORD_A.*))$ and Does Not Contain : (^((?!WORD_A).)*)$

This works fine if used alone, but I want to write something that can detect sth. like "Contains word A and Word B" (order not relevant!) and "Contains word A, but not Word B).

Basically I want that the user can make a statement like this "Starts with word A, Contains word B, but not C and/or ends with D" and the program returns true/false. The best thing would be to just append the regular expressions. Is this possible? I can't figure it out.

Upvotes: 2

Views: 814

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

For your example, I'd use lookahead assertions like this:

^WORD_A(?=.*WORD_B)(?!.*WORD_C).*WORD_D$

You can always add more conditions if you want (just add another lookahead). For example, if you want to match any string that contains WORD_A and WORD_B and does not contain WORD_C nor WORD_D:

^(?=.*WORD_A)(?=.*WORD_B)(?!.*WORD_C)(?!.*WORD_D)

Upvotes: 4

Related Questions