簡體   English   中英

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

[英]Can't get Pattern.matches(regExExpression) to work?

我有一個包含成千上萬個文件的目錄,這些文件遵循有限數量的不同命名約定。 我嘗試使用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

您的原始表達式似乎運行良好,如果我理解正確的問題,那么我們只需將[.]替換為\\. , 如果你希望:

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

演示版

測試

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可視化正則表達式:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM