Java 正则表达式函数重命名文件问题

Java 正则表达式函数重命名文件问题,java,regex,file-rename,Java,Regex,File Rename,我正在使用以下代码自动重命名文件: public static String getNewNameForCopyFile(final String originalName, final boolean firstCall) { if (firstCall) { final Pattern p = Pattern.compile("(.*?)(\\..*)?"); final Matcher m = p.matcher(originalName);

我正在使用以下代码自动重命名文件:

    public static String getNewNameForCopyFile(final String originalName, final boolean firstCall) {
    if (firstCall) {
        final Pattern p = Pattern.compile("(.*?)(\\..*)?");
        final Matcher m = p.matcher(originalName);
        if (m.matches()) { //group 1 is the name, group 2 is the extension
            String name = m.group(1);
            String extension = m.group(2);
            if (extension == null) {
                extension = "";
            }
            return name + "-Copy1" + extension;
        } else {
            throw new IllegalArgumentException();
        }
    } else {
        final Pattern p = Pattern.compile("(.*?)(-Copy(\\d+))?(\\..*)?");
        final Matcher m = p.matcher(originalName);
        if (m.matches()) { //group 1 is the prefix, group 2 is the number, group 3 is the suffix
            String prefix = m.group(1);
            String numberMatch = m.group(3);
            String suffix = m.group(4);
            return prefix + "-Copy" + (numberMatch == null ? 1 : (Integer.parseInt(numberMatch) + 1)) + (suffix == null ? "" : suffix);
        } else {
            throw new IllegalArgumentException();
        }
    }
}
这只适用于以下文件名我遇到问题,不知道如何调整代码: test.abc.txt 重命名后的文件将变为“test-Copy1.abc.txt”,但应为“test.abc-Copy1.txt”


你知道如何用我的方法实现这一点吗?

我想你要做的是在名字中找到最后一个“.”,对吗?我认为在这种情况下,您需要使用贪婪匹配。*(尽可能多的匹配)而不是。*

final Pattern p = Pattern.compile("(.*)(\\..*)")
您需要单独处理无圆点的情况:

if (originalName.indexOf('.') == -1) 
  return originalName + "-Copy1"
Your other code

如果我理解正确,您希望在文件名的最后一个点(
“.
)之前插入一个拷贝号(如果有),而在第一个点之前插入。这是因为您对第一组使用了不情愿的量词,而第二组能够匹配包含任意数量点的文件名尾部。我认为你会做得更好:

final Pattern p = Pattern.compile("(.*?)(\\.[^.]*)?");

请注意,如果存在,则第二组以点开头,但不能包含其他点。

返回前缀+“+”+后缀+“-复制“+numberMatch+”.txt”
这不适用于原始代码不处理的文件名中没有点的情况。关于贪婪量词和不情愿量词的观察是好的,但是我注意到它不能处理没有点的情况。你必须单独处理那件事。if(originalName.indexOf('.')==-1)需要以不同方式处理。我相信这将处理所有情况--零、一或多个点。这似乎有效,我将进一步测试,在所有测试通过后,我将接受答案,谢谢!