Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式文件名模式匹配_Java_Regex - Fatal编程技术网

Java 正则表达式文件名模式匹配

Java 正则表达式文件名模式匹配,java,regex,Java,Regex,我使用以下正则表达式: 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 =

我使用以下正则表达式:

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这样的文件名很好,但是如果有任何文件名为abc1.txt,上面的方法给出的是abc2.txt。如何设置regex条件或更改m.group2==null_copy+1:Integer.parseIntm.group2+1,这样它会将abc1\u copy1.txt作为新文件名返回给我,而不是像abc1\u copy2这样的abc2.txt等等。

我不是java爱好者,但一般来说,您应该使用libarry函数/类解析文件名,因为许多平台对它们有不同的规则

看看:

只需将-Integer.parseIntm.group2+1更改为m.group2+\u copy+1@RohitJain这将不起作用,因为它将继续添加_copy1
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);
    }
}