gpt4 book ai didi

Java 正则表达式 : Match any words word and must contain a certain work but except one word

转载 作者:行者123 更新时间:2023-11-29 08:24:41 26 4
gpt4 key购买 nike

我需要一个 Java 正则表达式来匹配除某个单词之外的任何单词,同时包含另一个单词。

例如字符串中不能包含Apple,但必须有Peach

Apple and Peach - Not match
Peach and Apple- Not match
Peach - Match
Three Peach - Match
Peach is good - Match
Peach is good, but Apple is bad - Not match

Apple Peach 不能出现在字符串中。

到目前为止我已经得到了这段代码。

^(?!(?:Apple)$)Peach$

最佳答案

如果你想匹配整个句子,你应该使用下面的正则表达式:

^(?!.*Apple).*Peach.*$

演示: https://regex101.com/r/G6RdPO/2/

此外,如果大小写不相关,那么您可以将正则表达式更改为:

(?i)^(?!.*Apple).*Peach.*$

最后但并非最不重要的一点是,您的问题中并不清楚应该如何处理 peachesapplespineapples(包含苹果)。如果您不想考虑它们,请使用:

(?i)^(?!.*\bApple\b).*\bPeach\b.*$

演示: https://regex101.com/r/G6RdPO/5

Apple and Peach - Not match
Peach and Apple- Not match
Peach - Match
Three Peach - Match
Peach is good - Match
Peach is good, but Apple is bad - Not match
Nothing - Not match
Peaches are good - Not match
Apples an Peaches - Not match
Pineapple and Peach - Match

如果你还想考虑它们的复数形式:

(?i)^(?!.*\bApple(?:s)?\b).*\bPeach(?:es)?\b.*$

演示: https://regex101.com/r/G6RdPO/4

Apple and Peach - Not match
Peach and Apple- Not match
Peach - Match
Three Peach - Match
Peach is good - Match
Peach is good, but Apple is bad - Not match
Nothing - Not Match
Peaches are good - Match
Apples an Peaches - Not match
Pineapple and Peach - Match

关于Java 正则表达式 : Match any words word and must contain a certain work but except one word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54084335/

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