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

时间:2012-05-23 08:04:36

标签: 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

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

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

谢谢!

2 个答案:

答案 0 :(得分:5)

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

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

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

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

答案 1 :(得分:1)

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

(......固定的后视/前方混乱)