Skip to content Skip to sidebar Skip to footer

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 ex

Solution 1:

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

Post a Comment for "Javascript Regex Excluding Certain Word/phrase?"