[英]How can I write a regular expression that will not match if a string contains a particular substring?
Example: 例:
Suppose in the following example I want to match strings that do not contain the word "NOOOT". 假设在下面的例子中我想匹配不包含单词“NOOOT”的字符串。
Example A: This shirt is NOOOT black.
Example B: This shirt is black.
I want something a little bit like the like the non-matching character class (eg [^abc]), but for whole strings: 我想要的东西有点像非匹配的字符类(例如[^ abc]),但对于整个字符串:
.*?(^NOOOT).*?
Does such a creature exist? 这样的生物存在吗?
^(?:(?!NOOOT).)*$
Explanation: 说明:
^
start of string ^
字符串的开头
(?!NOOOT).
assert that it's not possible to match NOOOT
at the current position, then match any character. 断言在当前位置不能匹配NOOOT
,然后匹配任何字符。
(?: ...)*
do this any number of times until... (?: ...)*
这样做任何次数,直到......
$
end of string. $
end of string。
You can do that wit a negative lookahead assertion (?!…)
: 你可以做一个负面的先行断言(?!…)
:
^(?:(?!NOOOT).)*$
This one matches only if there is no NOOOT
ahead at the current position while proceeding character by character. 只有当NOOOT
前进时,当前位置没有NOOOT
才会匹配。
It's also possible to do that with basic syntax. 使用基本语法也可以这样做。 But that's more complex. 但那更复杂。
Complementing regexes is a bad idea. 补充正则表达式是一个坏主意。 It's possible but really bad style, and may be inefficient; 它可能但风格非常糟糕,可能效率低下; and the negative assertions that allow you to do it concisely may only hide the inefficiency. 并且允许你简明扼要地做出的否定断言可能只能隐藏低效率。 Almost always the better idea is to match the regexp normally and invert the result with !
几乎总是更好的想法是正常匹配正则表达式并反转结果!
. 。
You should only ever compose negative regexes if you absolutely have to, eg if you must satisfy an API that can only be programmed by supplying one regext and nothing else. 如果你绝对必须,你应该只编写负正则表达式,例如,如果你必须满足只能通过提供一个regext而不是其他任何东西来编程的API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.