我使用正则表达式如下表达:正则表达式匹配文件名
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));
}
}
这工作正常filename
像abc.txt
但如果没有与名称abc1.txt
上述方法是给abc2.txt
的任何文件。如何使正则表达式条件或改变(m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1))
,使其返回我abc1_copy1.txt
为新的文件名,而不是abc2.txt
等等类似abc1_copy2
等
只要改变 - '(的Integer.parseInt(m.group(2))+ 1))''到(m.group(2)+ “_copy” + 1)' –
@RohitJain这不会工作,因为它会继续添加'_copy1' – user850234