【问题标题】:regex for finding files at a specific point in the file structure用于在文件结构中的特定点查找文件的正则表达式
【发布时间】:2022-10-13 13:18:06
【问题描述】:

我正在尝试使用正则表达式匹配在文件结构中具有特定深度的特定文件的文件路径,到目前为止我有

/^([A-Z]:\\)(.*?\\)(.*?\\)(.*?\\)(.*?\\)(?!.*\\)(<filename>)$/

炸开的样子:

/^
([A-Z]:\\)
(.*?\\)
(.*?\\)
(.*?\\)
(.*?\\)
(?!.*\\)
(<filename regex>)
$/

我遇到的问题是,如果不接受整个字符串,我似乎无法匹配文件名。

一些我不想工作的文件结构示例:

P:\example folder\example folder - 2\eample folder - 3\Rev 0\Example Folder - 4\example file.pdf

P:\example folder\Example Folder - 2\example file.pdf

与我需要匹配的内容相比:

P:\example folder\example folder - 2\eample folder - 3\Rev 0\example file.pdf

【问题讨论】:

  • 也许[^\\]* 而不是.*? 否则你会匹配任意深度
  • /^[A-Z]:\\([^\\]+\\){4}(filename)$/
  • 谢谢你!这不完全是我所需要的,但最终引导我找到了正确的答案
  • 也许您可以发布您的answer,以便其他人也可以从中受益?

标签: regex


【解决方案1】:

所以我仍在学习正则表达式,但是正如 jhnc 所说,我匹配的字符数量不正确,导致我的正则表达式失败。

我需要使用的是 jhnc [^\]* 描述的否定集,它查找转义字符反斜杠并匹配它之前的任何内容。

然后也找到文件名,我使用相同的否定集来搜索另一个反斜杠,以确保它没有超过 4 级文件,然后查找。和文件扩展名。

最终结果如下所示:

/^[A-Z]:\([^\]+\){4}([^\]+)(.)(w+)$/

/^
[A-Z]:\       -- find drive e.g. C:\
([^\]+\){4}  -- find 4 backslashes in the file path
([^\]+)       -- check if there is another backslash
(.)           -- find a period
(w+)          -- find any file extension
$/

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2022-11-02
    • 1970-01-01
    • 2010-11-05
    • 2012-06-16
    • 2011-05-10
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    相关资源
    最近更新 更多