【问题标题】:List file paths that match a regex when both path and filename contain wildcard当路径和文件名都包含通配符时,列出与正则表达式匹配的文件路径
【发布时间】:2012-07-19 06:44:46
【问题描述】:

我们的系统允许文件夹和文件都可以是正则表达式格式。例如

/dir1*/abcd/efg.? is legal. 

/dir* could match /dira and also /dirb/cde

我想查找与此模式匹配的所有文件。为了消除不必要的操作,我想获取根目录来启动文件列表和过滤。

是否有任何有效的方法来获取正则表达式路径模式的根目录?

几个测试用例:

/abc/def*/bc return /abc
/abc/def*    return /abc
/ab.c/def*   return /
/ab\.c/def*  return /ab.c

【问题讨论】:

  • 文件/文件夹路径中正则表达式的标准是什么?和bash一样吗?

标签: java regex file


【解决方案1】:

已编辑:添加了相对路径的处理

String path;
String root = path.replaceAll( "((?<=/)|((?<=^)(?=\\w)))(?!(\\w|\\\\\\.)+/.*).*", "" ) );

这是一个测试:

public static void main( String[] args ) throws IOException {
    String[] paths = {"/abc/def*/bc", "/abc/def*", "/ab.c/def*", "/ab\\.c/def*", "abc*", "abc/bc"};
    for ( String path : paths ) {
        System.out.println( path + " --> " + path.replaceAll( "((?<=/)|((?<=^)(?=\\w)))(?!(\\w|\\\\\\.)+/.*).*", "" ) );
    }
}

输出:

/abc/def*/bc --> /abc/
/abc/def* --> /abc/
/ab.c/def* --> /
/ab\.c/def* --> /ab\.c/
abc* --> 
abc/bc --> abc/

您可以从那里对其进行微调。

【讨论】:

  • 这只是为所有测试用例返回一个空字符串。
  • @Bohemian:确实。可能还有其他字符也可以转义,但是正如您所说,这应该很容易微调。 +1
  • 相对路径呢,比如“abc*”返回“”,“abc/bc*”返回“abc”? @Behemian
  • @JermaineXu 你没有问相对路径,你的例子都不是相对路径,但我也编辑了答案!
【解决方案2】:

使用这个正则表达式模式

^/([a-zA-Z]+[a-bA-Z0-9]+)/?.$

这将为您提供带有额外条件的根路径,即首字母应为字母

如果它也可以是一个数字,你可以简单地使用-

^/([a-bA-Z0-9]+)/?.$

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2016-12-11
    • 1970-01-01
    • 2022-10-19
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多