簡體   English   中英

正則表達式文件名模式匹配

[英]regex filename pattern match

我正在使用以下正則表達式:

Pattern p = Pattern.compile("(.*?)(\\d+)?(\\..*)?");

while(new File(fileName).exists())
{
    Matcher m = p.matcher(fileName);
    if(m.matches()) { //group 1 is the prefix, group 2 is the number, group 3 is the suffix
        fileName = m.group(1) + (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) + (m.group(3)==null ? "" : m.group(3));
    }
}

這對於abc.txt filename可以正常工作,但是如果存在任何名稱為abc1.txt的文件,則上述方法將給出abc2.txt 如何進行正則表達式條件或更改(m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1))以便返回abc1_copy1.txt為新文件名,而不是abc2.txt等,例如abc1_copy2等。

我不是Java專家,但是通常,您應該使用libarary函數/類來解析文件名,因為許多平台對其都有不同的規則。

查看: http : //people.apache.org/~jochen/commons-io/site/apidocs/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String

Pattern p = Pattern.compile("(.*?)(_copy(\\d+))?(\\..*)?");

while(new File(fileName).exists())
{
    Matcher m = p.matcher(fileName);
    if (m.matches()) {
        String prefix = m.group(1);
        String numberMatch = m.group(3);
        String suffix = m.group(4);
        int copyNumber = numberMatch == null ? 1 : Integer.parseInt(numberMatch) + 1;

        fileName = prefix;
        fileName += "_copy" + copyNumber;
        fileName += (suffix == null ? "" : suffix);
    }
}

暫無
暫無

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

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