【问题标题】:Java 1.7 String class matches method returns false when it should be trueJava 1.7 String 类匹配方法在应该为真时返回假
【发布时间】:2014-04-10 15:19:37
【问题描述】:
String s = "Remediation Release 16  - Test Status Report_04032014.xlsx";

s.matches("([^\\s]+(\\.(?i)(xlsx))$)"); // returns false

我已经在http://regex101.com/ 上尝试过这个例子,它说匹配是真的。

我缺少 match 方法的一些细微差别

【问题讨论】:

标签: java regex string


【解决方案1】:

您缺少开始和文件扩展名之间的整个文本。

尝试:

String s = "Remediation Release 16  - Test Status Report_04032014.xlsx";
//                                    | "Remediation" ... to ... "Report_04032014"
//                                    | is matched by ".+"
System.out.println(s.matches("([^\\s]+.+(\\.(?i)(xlsx))$)"));

输出

true

因为matches 匹配整个文本:

  • [^\\s] 将匹配您输入的开头。
  • .+ 将匹配文件名
  • (\\.(?i)(xlsx))$) 将匹配点+扩展名,不区分大小写,后跟输入结束

为了证明这一点:

//                           | removed outer group
//                           |      | added group 1 here for testing purposes
//                           |      |   | this is now group 2
//                           |      |   |               | removed outer group
Pattern p = Pattern.compile("[^\\s]+(.+)(\\.(?i)(xlsx))$");
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println("Group 1: " + m.group(1) + " | group 2: " + m.group(2));
}

输出

Group 1:  Release 16  - Test Status Report_04032014 | group 2: .xlsx

同样如所示,您不需要在初始 matches 参数中使用外括号。

【讨论】:

    【解决方案2】:

    在 java 中,matches() 确实对整个字符串执行匹配。所以你必须在你的正则表达式请求时使用.*

    s.matches(".*([^\\s]+(\\.(?i)(xlsx))$)");
               ^^ here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2016-12-20
      相关资源
      最近更新 更多