0

当字符串与关键字不匹配时,我需要一个返回某些内容(整个句子)的正则表达式。

也许这很奇怪,但我在 javascript 中需要这样的东西:

"any word".match(/.*(?!my key)/) => I would want ["any word"]
"my key".match(/.*(?!my key)/) => I would want null

这个以前的不起作用。

我不能做类似的事情,这会起作用:

if "any word".match(/my key/)
  return null
else
  return "any word"

因为我在一个接收正则表达式并在匹配时执行函数的地方。

4

1 回答 1

1

在你的正则表达式中,.*首先匹配整个字符串,然后前瞻断言(?!my key)也成功(因为你不能my key在字符串的末尾匹配,当然)。

你要

"test string".match(/^(?!.*my key).*/)

此外,如果您的测试字符串可能包含换行符,您可能需要使用s修饰符,并且您可能希望使用单词边界 ( \b) 来避免以下字符串的误报army keypad

"test string".match(/^(?!.*\bmy key\b).*/s)
于 2013-02-24T07:50:36.413 回答