无法使Pattern.matches(regExExpression)工作?

时间:2019-06-07 05:04:22

标签: java regex

我有一个包含成千上万个文件的目录,这些文件遵循一定数量的不同命名约定。我尝试使用RegEx来遍历文件名列表时帮助我识别文件命名约定。然后,我将使用此逻辑来选择正确的文件名解析方法。

这是我的代码:

//Define regex rule <br>
String regExRule = "Final_[0-9]{1,4}-[0-9]{1,4}([.][0-9]{1,3})_[A-Za-z0-9]+([.][0-9]{1,3})?[.]wav";

//Compile the rule <br>
Pattern p = Pattern.compile(regExRule);

//See if there is a match <br>
Matcher m = p.matcher("Final_0-1.1_FirstLast.4.wav");

//See if there is a match <br>
if(m.matches()){ //we have a match}



//   Always returns false even though I can confirm the rule works using
//this tool: https://www.regextester.com/

    Rule: <br>
    Final_[0-9]{1,4}-[0-9]{1,4}([.][0-9]{1,3})_[A-Za-z0-9]+([.][0-9]{1,3})?[.]wav

测试字符串:

Final_0-1.1_FirstLast.4.wav

1 个答案:

答案 0 :(得分:-1)

您的原始表达似乎运行良好,如果我理解正确的问题,那么,如果您愿意,我们将[.]替换为\.

Final_[0-9]{1,4}-[0-9]{1,4}(\.[0-9]{1,3})_[A-Za-z0-9]+([.][0-9]{1,3})?\.wav

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "Final_[0-9]{1,4}-[0-9]{1,4}(\\.[0-9]{1,3})_[A-Za-z0-9]+([.][0-9]{1,3})?\\.wav";
final String string = "Final_0-1.1_FirstLast.4.wav";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

RegEx电路

jex.im可视化正则表达式:

enter image description here