你错过了整个文本的开始和文件扩展名之间的细微差别一些。
尝试:
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
参数中使用外部圆括号。
可能重复[string.matches(正则表达式)返回false,但我认为它应该是真实的(http://stackoverflow.com/questions/14613621/string-matchesregex-returns-false-although-我认为它应该是真的) – devnull
请注意渲染在\的帖子其实是代码中的\\ – user1035795