python - 用于提取文件路径(不是 url)的通用正则表达式
问题描述
我正在尝试使用 Python 从文件中解析 url 和文件路径。我已经有一个 url 正则表达式。
问题
我想要一个从字符串中提取文件路径的正则表达式模式。要求:
- 独占(不包括网址)
- 独立于操作系统,即 Windows 和 UNIX 风格的路径,例如 (
C:\
,\\
,/
) - 所有路径类型,即绝对和相对路径,例如 (
/
,../
)
请通过修改下面的尝试或建议改进的模式来提供帮助。
试图
这是我到目前为止的正则表达式:
(?:[A-Z]:|\\|(?:\.{1,2}[\/\\])+)[\w+\\\s_\(\)\/]+(?:\.\w+)*
描述
(?:[A-Z]:|\\|(?:\.{1,2}[\/\\])+)
: 任何前面的驱动器号、反斜杠或虚线路径[\w+\\\s_\(\)\/]+
: 任何类似路径的字符 - 字母数字、斜杠、括号、下划线...(?:\.\w+)*
: 可选扩展
结果
re
注意:我已经使用字符串和模块的输入列表在 Python 中确认了这些结果。
预期的
这个正则表达式满足了我的大部分要求——即在提取大多数文件路径时排除 url。但是,我想匹配所有路径(包括以单斜杠开头的 UNIX 样式路径,例如/foo/bar.txt
)而不匹配 url。
研究
我还没有找到一个通用的解决方案。大多数工作倾向于满足特定情况。
所以帖子
外部站点
解决方案
您可以将问题拆分为 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)*
推荐阅读
- node.js - 如何使用 node-nlp 从句子中提取变量
- excel - 有没有办法判断当前运行的 Sub 是父级还是被调用的子级
- mysql - MariaDB:性能监控
- r - 当列具有不同的行数时使用 R 的布局
- f# - 结果绑定不同类型?
- laravel - Laravel 返回“未指定输入文件”。更改虚拟主机后
- list - 是否可以删除 SharePoint 视图页面上的列表名称?
- reactjs - 如何在反应中重定向到另一条路线?
- python - 将 Dataframe 作为新表导出到 MSSQL Server
- spring-boot - 防止在运行测试时触发 AOP(AspectJ) 代码