2013-01-18 147 views
1

我使用正则表达式如下表达:正则表达式匹配文件名

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)); 
    } 
} 

这工作正常filenameabc.txt但如果没有与名称abc1.txt上述方法是给abc2.txt的任何文件。如何使正则表达式条件或改变(m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)),使其返回我abc1_copy1.txt为新的文件名,而不是abc2.txt等等类似abc1_copy2

+0

只要改变 - '(的Integer.parseInt(m.group(2))+ 1))''到(m.group(2)+ “_copy” + 1)' –

+0

@RohitJain这不会工作,因为它会继续添加'_copy1' – user850234

回答

0
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); 
    } 
}