gpt4 book ai didi

regex - 检查字符串是否为 X 或不是 X

转载 作者:行者123 更新时间:2023-12-01 11:01:02 25 4
gpt4 key购买 nike

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

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

谢谢!

最佳答案

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

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

所以第一位匹配你好,然后是除空字符串之外的任何内容。 (我刚刚完成了自动机类(class),不禁将其视为 ε :P)。第二位匹配任何不以 hello 开头的内容.

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

关于regex - 检查字符串是否为 X 或不是 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10715845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com