JavaScript RegEx 不包括某些单词/短语?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7674172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:09:21  来源:igfitidea点击:

JavaScript RegEx excluding certain word/phrase?

javascriptregex

提问by vantrung -cuncon

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

如何编写 RegEx 模式来测试字符串是否包含具有以下结构的多个子字符串:

"cake.xxx"

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

其中 xxx不是“奶酪”或“牛奶”或“黄油”。

For example:

例如:

  • "I have a cake.honey and cake.egg"should return true, but
  • "I have a cake.**milk** and cake.egg"should return false.
  • "I have a cake.honey and cake.egg"应该返回true,但是
  • "I have a cake.**milk** and cake.egg"应该返回false

回答by stema

Is it this what you want?

这是你想要的吗?

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

See it here on Regexr

在 Regexr 上看到它

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

如果它包含“cake.XXX”而不是“cake.milk”或“cake.butter”,这将匹配完整的行

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

.*cake\.\w+.*如果有“蛋糕”,这部分将匹配。后跟至少一个 wrod 字符。

(?!.*cake\.(?:milk|butter))this is a negative lookahead, this will prevent matching if the string contains one of words you don't allow

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

^anchor the pattern to the start of the string

^将模式锚定到字符串的开头

回答by neaumusic

regex characters (like *, +, ?, and {0}) only apply to the last character

正则表达式字符(如*+?{0})仅适用于最后一个字符

you should put the word or phrase in a non-matching group, like so:

你应该把单词或短语放在一个不匹配的组中,像这样:

(?:someWord){0}means someWordis repeated (exists) 0 times, without putting it in your matches

(?:someWord){0}意思someWord是重复(存在)0次,没有把它放在你的比赛中

(?!someWord)does the same thing

(?!someWord)做同样的事情



regex101is a good playground for testing regex and seeing the breakdown

regex101是测试正则表达式和查看故障的好地方