David Tran
David Tran

Reputation: 10606

JavaScript RegEx excluding certain word/phrase?

How can I write a RegEx pattern to test if a string contains several substrings with the structure:

"cake.xxx"

where xxx is anything but not "cheese" or "milk" or "butter".

For example:

Upvotes: 22

Views: 38483

Answers (1)

stema
stema

Reputation: 92976

Is it this what you want?

^(?!.*cake\.(?:milk|butter)).*cake\.\w+.*

See it here on Regexr

this will match the complete row if it contains a "cake.XXX" but not when its "cake.milk" or "cake.butter"

.*cake\.\w+.* This part will match if there is a "cake." followed by at least one wrod character.

(?!.*cake\.(?:milk|butter)) this is a negative lookahead, this will prevent matching if the string contains one of words you don't allow

^ anchor the pattern to the start of the string

Upvotes: 30

Related Questions