【问题标题】:Java regex to prevent match for specific keywordsJava 正则表达式以防止匹配特定关键字
【发布时间】:2017-06-09 18:04:15
【问题描述】:

我一直在探索负面展望和负面展望。但他们似乎没有做我想做的事。

假设我有一个句子“word1 word2 word3 word4”,如果该句子中存在 word3 或 word7,我需要一个 拒绝 匹配的正则表达式。换句话说,matcher.find() 应该是 false。我该怎么做?

理想情况下,我希望捕获的句子尽可能放松.*,但是如果我收紧捕获的句子,我只能阻止匹配,请参阅下面的 (\\w{4}\\d{1}\\s.*) 部分,其结尾为 //Result: Nothing

    String contents = null;
    contents = "word1 word2 word3 word4";
    m = Pattern.compile("(?i)(.*)").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(?!.*(word3))(.*)").matcher(contents);
    //Result: ord3 word4

    m = Pattern.compile("(?i)(?!.*(word3))(\\w{4}\\d{1}\\s.*)").matcher(contents);
    //Result: Nothing

    m = Pattern.compile("(?i)(?<!(word3))(.*)").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(.*)(?<!(word3))").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(.*)(?<!(word4))").matcher(contents);
    //Result: word1 word2 word3 word

【问题讨论】:

  • 我不熟悉消极的笨蛋,但有两条一般性建议:Regex 对我来说似乎不是正确的工具,当您确实需要使用 regex 时,我可以推荐本站调试:regex101.com
  • 先检查句子中是否存在单词,如果不存在,应用匹配器?

标签: java regex


【解决方案1】:

怎么样:

Pattern pattern = Pattern.compile("^(?!.*(word1|word2|word3|word4|word5|word6|word7)).*$");
Matcher matcher = patter.matcher(" word1");
System.out.println(matcher.find());

这可以根据这些词中的模式进行简化,例如:

Pattern p = Pattern.compile("^(?!.*(word[1-7])).*$");
Matcher m = p.matcher(" word8");
boolean b = m.find();

【讨论】:

  • 谢谢@grzegorz-górkiewicz 现在意识到我的错误。我错过了 ^... $
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多