Skip to main content
 首页 » 编程设计

python之从文本中提取文件路径

2025年05月04日15lonelyxmas

我有一个文本文件,其中包含各种类型的路径和目录以及一些 URL。我正在尝试获取不包括 URL 和 Windows 目录 (c:/) 的不同路径。

txt = r''' 
\Files\System\ado\ 
 
C:\Dir\me\match1\poq!"&\file.txt 
 
http://example/uploads/ssh/ 
 
{drive of encrypted files}\FreezedByWizard.README.TXT 
 
%Program Files%\Common Files\System\ado\ 
 
/home/user/web/other.longextension 
''' 

正确的输出:

\Files\System\ado\ 
 
{drive of encrypted files}\ 
 
%Program Files%\Common Files\System\ado\ 
 
/home/user/web/ 

我尝试了各种正则表达式,包括这些正则表达式,但我无法获得正确的结果。

pattern = re.compile(r'(?:/[^/]+)*',re.I) 
# pattern = re.compile(r'\b(\\.+\\|\/.+\/|\%.+\%)(?:[^\/]|\\\/)+?\b',re.I)  
# this one for example prints all subdirectories not the main one! 
 
matches = re.findall(pattern,txt) 
print(matches) 

请您参考如下方法:

我注意到您想要的行以 \{ % 或/ 开头。也许像这样简单的事情对您有用?

^(?:\\|\{|\%|\/).+(?:\\|/) 

Regex Demo

^                start at line start 
(?:\\|\{|\%|\/)  non-matching group with different string starts 
.+               match any character 
(?:\\|/)         match until reaches \ or / 

Online Code Editor

pattern = re.compile(r'^(?:\\|\{|\%|\/).+(?:\\|/)', re.M)