Java正则表达式文件扩展名。

3

我需要检查文件名是否以gzip扩展名结尾。具体来说,我正在寻找两个扩展名:".tar.gz"和".gz"。我希望使用一个正则表达式捕获文件名(和路径)作为一个组,如果有gzip扩展名,则排除它。
我在此示例路径上测试了以下正则表达式:

String path = "/path/to/file.txt.tar.gz";
  1. Expression 1:

    String rgx = "(.+)(?=([\\.tar]?\\.gz)$)";
    
  2. Expression 2:

    String rgx = "^(.+)[\\.tar]?\\.gz$";
    

以这种方式提取第一组:

Matcher m = Pattern.compile(rgx).matcher(path);           
if(m.find()){
   System.out.println(m.group(1));
}

两个正则表达式都会给我相同的结果:/path/to/file.txt.tar而不是/path/to/file.txt。 任何帮助都将不胜感激。 提前致谢。

1
如果你正在寻找 .tar.gz.gz,难道你不只是在寻找 .gz 吗?所有的 .tar.gz 都可以被一个捕获 .gz 的表达式所捕获。 - Captain Man
小注释。你的 [\\.tar] 应该改为 (\\.tar),因为 [...] 表示字符组。 - aioobe
3个回答

4
您可以使用以下习语一次匹配路径+文件名和gzip扩展名:
String[] inputs = {
        "/path/to/foo.txt.tar.gz", 
        "/path/to/bar.txt.gz",
        "/path/to/nope.txt"
 };
//                           ┌ group 1: any character reluctantly quantified
//                           |    ┌ group 2
//                           |    | ┌ optional ".tar"
//                           |    | |       ┌ compulsory ".gz"
//                           |    | |       |     ┌ end of input
Pattern p = Pattern.compile("(.+?)((\\.tar)?\\.gz)$");
for (String s: inputs) {
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.printf("Found: %s --> %s %n", m.group(1), m.group(2));
    }
}

输出

Found: /path/to/foo.txt --> .tar.gz 
Found: /path/to/bar.txt --> .gz 

3
您需要将与文件名reluctant匹配的部分进行更改,即将(.+)改为(.+?)
String rgx = "^(.+?)(\\.tar)?\\.gz";
//              ^^^

现在你获得:
Matcher m = Pattern.compile(rgx).matcher(path);           
if(m.find()){
   System.out.println(m.group(1));   //   /path/to/file.txt
}

1
使用基于捕获组的正则表达式。
^(.+)/(.+)(?:\\.tar)?\\.gz$

并且,

从索引1获取路径。

从索引2获取文件名。

DEMO


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接