【问题标题】:Check that all lines match regex pattern in Java检查所有行是否与 Java 中的正则表达式模式匹配
【发布时间】:2013-05-21 12:00:44
【问题描述】:

如何检查所有行是否与 Java 中的正则表达式模式匹配。

我的意思是我可以自己在 while 循环中分割行。但是是否有任何库或标准 API 可以实现此功能?

更新这是 Ruby 解决方案:

if text =~ /PATTERN/

【问题讨论】:

  • 到目前为止你有什么?
  • Afaik 没有具有此功能的本机方法。为什么还要为最多 5 行代码的方法引入整个库?
  • 如果它只适用于 1 个正则表达式,我认为 diy 会更有效率。再看看 Cup 和 JFlex。
  • 我必须使用此代码检查电子邮件报价拆分,例如“AK>> Bob> >

标签: java regex pattern-matching


【解决方案1】:

这是一个使用 Guava 的实用方法,如果提供的文本中的每一行都与提供的模式匹配,则返回 true:

public static boolean matchEachLine(String text, Pattern pattern){
    return FluentIterable.from(Splitter.on('\n').split(text))
                         .filter(Predicates.not(Predicates.contains(pattern)))
                         .isEmpty();
}

【讨论】:

    【解决方案2】:

    这是我用的一个

    public static boolean multilineMatches(final String regex, final String text) {
        final Matcher m = Pattern.compile("^(.*)$", Pattern.MULTILINE).matcher(text);
        final Pattern p = Pattern.compile(regex);
        while(m.find()) {
            if (!p.matcher(m.group()).find()) {
                return false;
            }
        }
        return true;
    }
    

    【讨论】:

      【解决方案3】:

      我知道没有标准的 API 功能可以做到这一点,但是,这样的事情很容易:

      string.matches("(What you want to match(\r?\n|$))*+")
      

      用法:

      String string = "This is a string\nThis is a string\nThis is a string";
      System.out.println(string.matches("(This is a string(\r?\n|$))*+"));
      

      \r?\n 涵盖了最常见的换行符。
      $ 是字符串的结尾。
      (\r?\n|$) 是换行符或字符串的结尾。
      *+ 为零或更多 - 但这是a possessive qualifier

      所以整个事情基本上检查每一行是否匹配This is a string

      如果你想在函数中使用它:

      boolean allLinesMatch(String string, String regex)
      {
        return string.matches("(" + regex + "(\r?\n|$))*+");
      }
      

      Java regex reference.

      为什么需要所有格限定词的主要例子:

      如果您将字符串 This is a string. 重复几次(准确地说是 34 次),但最后一个字符串是 This is a string.s(与正则表达式不匹配)并且 What you want to match.* .* .*\\.,那么您最后用* 等待了很长一段时间。

      * example - 在我的机器上运行 - 超过 几个小时,之后我停止了它。

      *+ example - 我机器上的运行时间 - 不到 一秒

      请参阅Catastrophic Backtracking 了解更多信息。

      【讨论】:

      • 这可能非常低效。查找“灾难性回溯正则表达式”。
      • @StephenC 添加了所有格限定符和一个不错的小测试用例。
      猜你喜欢
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      相关资源
      最近更新 更多