开发者

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 return true, but
  • "I have a cake.**milk** and cake.e开发者_如何学编程gg" should return false.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜