检查字符串是X还是不是X.

mat*_*tte 3 regex

我可以检查字符串是否等于具有正则表达式的给定关键字.这是一个例子:

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
Run Code Online (Sandbox Code Playgroud)

我无法实现的是检查字符串是否不等于关键字.以下是我想要做的一些例子:

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"
Run Code Online (Sandbox Code Playgroud)

我想我很接近^(?!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
Run Code Online (Sandbox Code Playgroud)

谢谢!

Tik*_*vis 5

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

^(hello.+|(?!hello).*)$
Run Code Online (Sandbox Code Playgroud)

所以第一位匹配hello,然后保存空字符串.(我刚刚完成了一个自动机类,不禁将其视为ε:P).第二位匹配任何不以开头的东西hello.

我想,这涵盖了所有可能的情况.