【问题标题】:Java Regex: Match any words word and must contain a certain work but except one wordJava Regex:匹配任何单词单词并且必须包含某个作品,但除了一个单词
【发布时间】:2019-06-02 16:55:16
【问题描述】:

我需要一个 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$

【问题讨论】:

    标签: java regex


    【解决方案1】:

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

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

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

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

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

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

    (?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
    

    【讨论】:

    • 太棒了。它有效,感谢您的解释。
    【解决方案2】:

    您应该使用.* 匹配字符串开头和您要查找的关键字之间的任何字符:

    ^(?!.*Apple).*Peach
    

    演示:https://regex101.com/r/t3Dz4E/1

    【讨论】:

    • 你的正则表达式不会匹配整行,一旦遇到Peach就会停止,你应该在Peach之后添加.*$以获得整个东西。
    • .*$ 完全是多余的。
    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多