我必须检查文件名是否以gzip扩展名结尾。特别是我正在寻找两个扩展名:“。star.gz”和“.gz”。我想使用单个正则表达式将文件名(和路径)捕获为一个组,不包括gzip扩展名(如果有的话)。 我在此示例路径上测试了以下正则表达式
String path = "/path/to/file.txt.tar.gz";
表达式1:
String rgx = "(.+)(?=([\\.tar]?\\.gz)$)";
表达式2:
String rgx = "^(.+)[\\.tar]?\\.gz$";
以这种方式提取第1组:
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
。
任何帮助将不胜感激。
提前致谢
答案 0 :(得分: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
答案 1 :(得分: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
}
答案 2 :(得分:1)