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

これはfilenamelikeでも問題abc.txtなく動作しますが、名前の付いたファイルがある場合はabc1.txt、上記のメソッドが与えabc2.txtます。正規表現の条件を作成する方法、または新しいファイル名として(m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1))返されるように変更する方法など。abc1_copy1.txtabc2.txtabc1_copy2

4

2 に答える 2

0

私はJavaの人ではありませんが、多くのプラットフォームでは異なるルールがあるため、一般に、ファイル名の解析にはライブラリ関数/クラスを使用する必要があります。

見てください:http: //people.apache.org/~jochen/commons-io/site/apidocs/org/apache/commons/io/FilenameUtils.html#getBaseName (java.lang.String )

于 2013-01-18T19:21:12.713 に答える
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);
    }
}
于 2013-01-18T19:41:47.683 に答える