JavaScript RegEx不包括某些单词/短语? [英] JavaScript RegEx excluding certain word/phrase?
问题描述
如何编写一个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 returntrue
, but"I have a cake.**milk** and cake.egg"
should returnfalse
.
推荐答案
这是你想要的吗?
^(?!.*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屋!