Omer
Omer

Reputation: 15

Regular Expression to exclude a list of words

I am requested to enforce a regex behavior that will allow a user to fill a certain field under the following behavior:

^[a-z A-Z0-9\s]+$

However, in addition, I have a list of certain words that the user should not be allowed to insert.

I've used the following RegEx:

^((?!WordA|WordB).)[a-z A-Z0-9\s]+$

However, this disables any string starting with these words, while I need to disable only strings that are EQUAL to the words.

Any suggestion?

Upvotes: 1

Views: 6473

Answers (1)

d0nut
d0nut

Reputation: 2834

All you have to do is make the negative lookahead assure that the strings don't don't after each word like so:

^(?!(WordA|WordB)$)[a-z A-Z0-9\s]+$

Also, your part here: [a-z A-Z0-9\s] should really be [a-zA-Z0-9\s] (without the space) since \s matches spaces.

Upvotes: 2

Related Questions