I am using the below regex expression :
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));
}
}
This works fine for filename like abc.txt but if there is any file with name abc1.txt the above method is giving abc2.txt. How to make the regex condition or change (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) so that it returns me abc1_copy1.txt as new filename and not abc2.txt and so forth like abc1_copy2 etc.
1 Answer