4

我可以使用正则表达式检查字符串是否等于给定关键字。这是一个例子:

Regex: /^hello$/
String: hello
Result: matches, as expected

Regex: /^goodbye$/
String: goodbye
Result: matches, as expected

Regex: /^bye$/
String: bye bye
Result: does not match, as expected

我无法实现的是检查字符串是否不等于关键字。以下是我正在尝试做的一些示例:

Regex: ^(?!hello).*$
String: bye
Result: matches, as expected

Regex: ^(?!hello).*$
String: bye bye
Result: matches, as expected

Regex: ^(?!hello).*$
String: say hello
Result: matches, as expected

Regex: ^(?!hello).*$
String: hello you
Result: does not match, but should match because "hello you" is not equal to "hello"

我想我很接近,^(?!hello).*$但需要帮助。这是另一个例子:

Regex: ^(?!fresh\sfruits).*$
String: fresh fruits
Result: does not match, as expected

Regex: ^(?!fresh\sfruits).*$
String: lots of fresh fruits
Result: matches, as expected

Regex: ^(?!fresh\sfruits).*$
String: fresh fruits, love them.
Result: does not match, but should match

谢谢!

4

2 回答 2

5

让我们将失败的情况添加到您的表达式中:

^(hello.+|(?!hello).*)$

所以第一位匹配 hello 后跟任何保存空字符串的内容。(我刚刚完成了一个自动机课程,不禁将其视为 ε:P)。第二位匹配不以 开头的任何内容hello

我认为这涵盖了所有可能的情况。

于 2012-05-23T08:18:30.363 回答
1

^(?!hello$)(放下.*

(...固定后视/前瞻混淆)

于 2012-05-23T08:07:05.887 回答