首页 > 解决方案 > 用于提取文件路径(不是 url)的通用正则表达式

问题描述

我正在尝试使用 Python 从文件中解析 url 和文件路径。我已经有一个 url 正则表达式。

问题

我想要一个从字符串中提取文件路径的正则表达式模式。要求:

请通过修改下面的尝试或建议改进的模式来提供帮助。

试图

这是我到目前为止的正则表达式:

(?:[A-Z]:|\\|(?:\.{1,2}[\/\\])+)[\w+\\\s_\(\)\/]+(?:\.\w+)*

描述

结果

在此处输入图像描述

re注意:我已经使用字符串和模块的输入列表在 Python 中确认了这些结果。

预期的

这个正则表达式满足了我的大部分要求——即在提取大多数文件路径时排除 url。但是,我想匹配所有路径(包括以单斜杠开头的 UNIX 样式路径,例如/foo/bar.txt)而不匹配 url。

研究

我还没有找到一个通用的解决方案。大多数工作倾向于满足特定情况。

所以帖子

外部站点

标签: pythonregex

解决方案


您可以将问题拆分为 3 种替代模式:( 请注意,我没有为路径/文件名实现所有字符排除)

  • 未引用的 Windows 路径
  • 引用的 Windows 路径
  • Unix路径

这会给出这样的结果:

((((?<!\w)[A-Z,a-z]:)|(\.{1,2}\\))([^\b%\/\|:\n\"]*))|("\2([^%\/\|:\n\"]*)")|((?<!\w)(\.{1,2})?(?<!\/)(\/((\\\b)|[^ \b%\|:\n\"\\\/])+)+\/?)

分解:

Wind-Non-Quoted: ((((?<!\w)[A-Z,a-z]:)|(\.{1,2}\\))([^\b%\/\|:\n\"]*))
Wind-Quoted:     ("\2([^%\/\|:\n\"]*)")
Unix:            ((?<!\w)(\.{1,2})?(?<!\/)(\/((\\\b)|[^ \b%\|:\n\"\\\/])+)+\/?)


Wind-Non-Quoted:
    prefix: (((?<!\w)[A-Z,a-z]:)|(\.{1,2}\\))
         drive: ((?<!\w)[A-Z,a-z]:) *Lookback to ensure single letter*
      relative: (\.{1,2}\\))
      path: ([^\b%\/\|:\n\"]*))     *Excluding invalid name characters (The list is not complete)*

Wind-Quoted:
    prefix: \2                *Reuses the one from non-Quoted*
      path: ([^%\/\|:\n\"]*)  *Save as above but does not exclude spaces*

Unix:
    prefix: (?<!\w)(\.{1,2})?                . or .. not preceded by letters
      path: (?<!\/)                          repeated /name (exclusions as above)
            (\/((\\\b)|[^ \b%\|:\n\"\\\/])+) not preceded by /
            \/?                              optionally ending with /

            *(excluding the double slashes is intended to prevent matching urls)*

推荐阅读