gpt4 book ai didi

java - 正则表达式文件名模式匹配

转载 作者:行者123 更新时间:2023-12-01 04:54:29 24 4
gpt4 key购买 nike

我正在使用以下正则表达式:

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 等。

最佳答案

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

关于java - 正则表达式文件名模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14406035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com