Python 使用正则表达式从给定目录提取文件名
我的正则表达式很弱。我正在寻找有关如何从以下字符串中提取Python 使用正则表达式从给定目录提取文件名,python,regex,python-3.x,Python,Regex,Python 3.x,我的正则表达式很弱。我正在寻找有关如何从以下字符串中提取.sav文件名的帮助: C:\Users…\Standard Loadflows Seq and Dyn PSSEv34- 2019-02-20\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav 目前我正在使用此代码: re.findall(r'\\(.+).sav',txt) 但它只能找到 ['Users\\…\\S
.sav
文件名的帮助:
C:\Users…\Standard Loadflows Seq and Dyn PSSEv34-
2019-02-20\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav
目前我正在使用此代码:
re.findall(r'\\(.+).sav',txt)
但它只能找到
['Users\\…\\Standard Loadflows Seq and Dyn PSSEv34-2019-02-20\\AutumnHi-20180531-183047-34-SystemNormal\AutumnHi-20180531-183047-34-SystemNormal.sav']
我正在尝试查找“AutumnHi-20180531-183047-34-SystemNormal.sav”
我正在使用Python 3.7。Regex101():
您可以在不使用re
模块的情况下实现相同的功能:
print(txt.split('\\')[-1])
以下模式应与文件名匹配:
(?=[^\\]*$).\\.sav
上面的模式断言(
?=
is)字符串末尾没有其他字符是反斜杠。因此,基本上它会找到最后一个反斜杠,然后匹配所需的文本。有关其他详细信息,请参阅上面链接中regex101演示右侧的“解释”。您可以匹配反斜杠,然后使用否定字符类在与非反斜杠匹配的组中捕获。然后匹配一个点和sav
您可以使用一个负的前瞻来断言直接在右边的不是非空白字符
\\([^\\]+\.sav)(?!\S)
我假设您不是在学习regex,而是想知道如何处理解析文件名 我将使用pathlib模块来处理对文件名的解析
C:\Users\barry>py -3.7
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pathlib
>>> filename = r'C:\Users\...\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\WinterLo-20180729-043047-34-SystemNormal\WinterLo-20180729-043047-34-SystemNormal.sav'
>>> path = pathlib.Path(filename)
>>> path.name
'WinterLo-20180729-043047-34-SystemNormal.sav'
>>> path.parent
WindowsPath('C:/Users/.../Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20/WinterLo-20180729-043047-34-SystemNormal')
>>>
我猜这些表达方式:
[^\\]+\.sav
([^\\]+\.sav)
或者类似的衍生物可能会提取我们想要的东西
试验
输出
这回答了你的问题吗?
C:\Users\barry>py -3.7
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pathlib
>>> filename = r'C:\Users\...\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\WinterLo-20180729-043047-34-SystemNormal\WinterLo-20180729-043047-34-SystemNormal.sav'
>>> path = pathlib.Path(filename)
>>> path.name
'WinterLo-20180729-043047-34-SystemNormal.sav'
>>> path.parent
WindowsPath('C:/Users/.../Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20/WinterLo-20180729-043047-34-SystemNormal')
>>>
[^\\]+\.sav
([^\\]+\.sav)
import re
print(re.findall(r"([^\\]+\.sav)", "C:\\Users...\\Standard Loadflows Seq and Dyn PSSEv34 - 2019-02-20\\AutumnHi-20180531-183047-34-SystemNormal\\AutumnHi-20180531-183047-34-SystemNormal.sav"))
['AutumnHi-20180531-183047-34-SystemNormal.sav']