我有一个文本文件,其中包含各种类型的路径和目录以及一些 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)
请您参考如下方法:
我注意到您想要的行以 \{ % 或/ 开头。也许像这样简单的事情对您有用?
^(?:\\|\{|\%|\/).+(?:\\|/)
^ start at line start
(?:\\|\{|\%|\/) non-matching group with different string starts
.+ match any character
(?:\\|/) match until reaches \ or /
pattern = re.compile(r'^(?:\\|\{|\%|\/).+(?:\\|/)', re.M)
