我正在尝试编写一个正则表达式来匹配任何不是"foo“和"bar”的内容。我在Regular expression to match a line that doesn't contain a word?上发现了如何匹配除一个单词之外的任何单词,但我对正则表达式不是很熟练,不确定如何在这个标准中添加第二个单词。
如有任何帮助,将不胜感激!
澄清:
我想匹配任何不是foo或bar的东西。
发布于 2011-07-26 21:35:32
对这个问题的回答:“一个正则表达式来匹配任何不是"foo”和“”的内容?“
^(?!foo$|bar$).*
就是这么做的。
^ # Start of string
(?! # Assert that it's impossible to match...
foo # foo, followed by
$ # end of string
| #
bar$ # bar, followed by end of string.
) # End of negative lookahead assertion
.* # Now match anything
如果字符串可以包含您也希望匹配的换行符,则可能需要设置RegexOptions.Singleline
。
发布于 2011-07-26 21:37:37
对以下问题的回答:"How to a second word to ?"“
您链接到的问题的答案是:
^((?!word).)*$
在这里,(?!word)
是一个负面的前瞻。这个问题的答案是:
^((?!wordone|wordtwo).)*$
对这两个词都有效。注:如果您有多行,并且希望每行都匹配,则应启用全局和多行选项,如另一个问题所示。
不同之处在于否定的先行条款:(?!wordone|wordtwo)
。它可以扩展到任何(合理)数量的单词或子句。
有关详细说明,请参阅this answer。
发布于 2011-07-26 21:59:14
我知道你想做什么,但你想阻止/允许什么的细节有点不清楚。例如,你想阻止任何不是 foo
或bar
的东西吗?或者你想阻止任何包含这两个字符串的?
它们是否可以是另一个字符串的一部分,如@Tim的foonly
或bartender
示例?
我只会给出每种模式的建议:
/^(?!foo$|bar$).*/ #credit to @Tim Pietzcker for this one, he did it first
#blocks "foo"
#blocks "bar"
#allows "hello goodbye"
#allows "hello foo goodbye"
#allows "foogle"
#allows "foobar"
/^(?!.*foo|.*bar).*$/
#blocks "foo"
#blocks "bar"
#allows "hello goodbye"
#blocks "hello foo goodbye"
#blocks "foogle"
#blocks "foobar"
/^(?!.*\b(foo|bar)\b).*$/
#blocks "foo"
#blocks "bar"
#allows "hello goodbye"
#blocks "hello foo goodbye"
#allows "foogle"
#allows "foobar"
https://stackoverflow.com/questions/6830796
复制相似问题