【问题标题】:String.matches() and matcher.matches() return different results [closed]String.matches() 和 matcher.matches() 返回不同的结果 [关闭]
【发布时间】:2019-12-26 06:32:10
【问题描述】:

在下面的代码示例中,matcher.matches() 和 String.matches 没有返回相同的结果,我不明白为什么:

    String MIDDLESIGN = "[(\\/)"+"|"+"(\\*)"+"|"+"(\\++)"+"|"+"(\\-+)]";
    String x = "1 +++ 2 * 3 -- 4";
    System.out.println("1 +++ 2 * 3 -- 4".matches("(\\d+\\s+"+MIDDLESIGN+"*"+"\\s+\\d*)+")); //true

    Pattern pattern = Pattern.compile((\\d+\\s+"+MIDDLESIGN+"*"+"\\s+\\d*)+");
    Matcher matcher = pattern.matcher(x);

    System.out.println(matcher.matches()); //false

知道为什么会有这种差异吗?

【问题讨论】:

标签: java


【解决方案1】:

您的代码中似乎存在问题:

它工作正常:result

String MIDDLESIGN = "[(\\/)"+"|"+"(\\*)"+"|"+"(\\++)"+"|"+"(\\-+)]";
String x = "1 +++ 2 * 3 -- 4";
System.out.println("1 +++ 2 * 3 -- 4".matches("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+")); // true

Pattern pattern = Pattern.compile("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+");
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.matches()); // true

来自您的代码: Pattern.compile((\d+\s+"+MIDDLESIGN+""+"\s+\d)+");

其中缺少"。用下面的代码替换它:

Pattern pattern = Pattern.compile("(\\d+\\s+" + MIDDLESIGN + "*" + "\\s+\\d*)+");

【讨论】:

    猜你喜欢
    • 2011-01-28
    • 2014-12-29
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多