![](/img/trans.png)
[英]RegEx to match a string of two words but not match t if it has the third
[英]Regex to match anything but two words
我正在嘗試編寫一個正則表達式以匹配非“ foo”和“ bar”的任何內容。 我發現了如何在正則表達式中匹配除一個單詞以外的任何單詞, 以匹配不包含單詞的行? 但是我對正則表達式不是很熟練,並且不確定如何在此critera中添加第二個單詞。
非常感激任何的幫助!
澄清:
我想匹配不是foo或bar的任何東西。
對問題的答案:“一個正則表達式可以匹配不是“ foo”和“ bar”的任何內容?”
^(?!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
。
我知道您要執行的操作,但是您要阻止/允許執行的操作的細節尚不清楚。 例如,您是否要阻止不完全是 foo
或bar
任何內容? 還是要阻止包含這兩個字符串的任何內容?
他們可以是另一個字符串的一部分,如@蒂姆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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.