JavaScript RegEx不包括某些单词/短语? [英] JavaScript RegEx excluding certain word/phrase?

查看:93
本文介绍了JavaScript RegEx不包括某些单词/短语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个RegEx模式来测试一个字符串是否包含几个带有结构的子串:

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

"cake.xxx"

其中xxx是任何东西,但不是奶酪或牛奶或者黄油。

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

例如:


  • 我有一个cake.coney和cake.egg应该返回 true ,但是

  • 我有一个蛋糕。**牛奶**和cake.egg应该返回 false

  • "I have a cake.honey and cake.egg" should return true, but
  • "I have a cake.**milk** and cake.egg" should return false.

推荐答案

这是你想要的吗?

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

请参阅此处的Regexr

这将匹配整行,如果它包含cake.XXX但不是当它的cake.milk或cake.butter

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

。* cake \.\ w +。* 如果有蛋糕,此部分将匹配。其次是至少一个wrod字符。

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

(?!。* cake \。(?:milk | butter))这是一个负向前瞻,如果字符串包含您不允许的单词之一,这将阻止匹配

(?!.*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

这篇关于JavaScript RegEx不包括某些单词/短语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆