[英]Regexp that matches when word is not found
I need a regexp that returns something (the entire sentence) when the string does NOT match a keyword. 我需要一个正则表达式,当字符串与关键字不匹配时,该表达式将返回某些内容(整个句子)。
Maybe this is strange, but I need something like this in javascript: 也许这很奇怪,但是我需要在javascript中执行以下操作:
"any word".match(/.*(?!my key)/) => I would want ["any word"]
"my key".match(/.*(?!my key)/) => I would want null
This previous does not work. 此先前无效。
I can't do something like, which would work: 我不能做这样的事情,这将工作:
if "any word".match(/my key/)
return null
else
return "any word"
because I am inside a place that receives a Regexp and executes a function if it matches. 因为我在一个可以接收Regexp并执行匹配功能的地方。
In your regex, .*
first matches the entire string, then the lookahead assertion (?!my key)
succeeds, too (because you can't match my key
at the end of the string, of course). 在您的正则表达式中, .*
首先匹配整个字符串,然后超前断言(?!my key)
成功(因为您当然不能在字符串末尾匹配my key
)。
You want 你要
"test string".match(/^(?!.*my key).*/)
Also, you might need to use the s
modifier if your test string possibly contains newlines, and you might want to use word boundaries ( \\b
) to avoid false positives with strings like army keypad
: 另外,如果测试字符串中可能包含换行符,则可能需要使用s
修饰符,并且您可能希望使用单词边界( \\b
)来避免对诸如army keypad
这样的字符串产生误报:
"test string".match(/^(?!.*\bmy key\b).*/s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.