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:
"I have a cake.honey and cake.egg"
should returntrue
, but"I have a cake.**milk** and cake.e开发者_如何学编程gg"
should returnfalse
.
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
精彩评论