需要python正则表达式的帮助吗
我有目录中的文件列表:需要python正则表达式的帮助吗,python,Python,我有目录中的文件列表: gp_dump_0_10_20171112003450 <== gp_dump_0_11_20171112003450 <== gp_dump_0_12_20171112003450 <== gp_dump_0_13_20171112003450 <== gp_dump_0_14_20171112003450 <== gp_dump_1_1_20171112003450 <== gp_dump_1_1_20171112003450_po
gp_dump_0_10_20171112003450 <==
gp_dump_0_11_20171112003450 <==
gp_dump_0_12_20171112003450 <==
gp_dump_0_13_20171112003450 <==
gp_dump_0_14_20171112003450 <==
gp_dump_1_1_20171112003450 <==
gp_dump_1_1_20171112003450_post_data
gp_dump_20171112003450_ao_state_file
gp_dump_20171112003450_co_state_file
gp_dump_20171112003450_last_operation
gp_dump_20171112003450.rpt
编辑:将regex更改为匹配end,运行此操作后,我没有得到任何结果。两个主要方面:
re.match
,而不是re.finditer
<如果模式与开头的字符串匹配,则code>re.match将返回匹配对象;如果不匹配,则返回None
gp_dump_1_1_20171112003450_post_数据,因为它以匹配开头。正则表达式中的$
元字符表示字符串的结尾,因此如果将其放在模式的结尾,它将不会将字符串与尾随字符匹配
import os
import re
dump_key = 20171112003450
backup_files = os.listdir('/home/jadhavy/backup/')
segment_file_regex = "gp_dump_\d+?_\d+?_%s$" %dump_key
for file in backup_files:
if re.match(segment_file_regex,file,re.S):
print(file)
其他三个小贴士:
re.S
标志,因为它只影响
元字符r'\n'
变为'\\n'
,而不是'\n'
(换行符)re.escape
转义元字符。例如r'abc%sghi'%re.escape('[def]')
变成r'abc\[def\]ghi'
而不是r'abc[def]ghi'
,后者不是您想要的正则表达式李>
您不需要
\d+?\uu
,因为下划线无论如何都会停止匹配。这提醒我,如果要匹配0或更多数字,您也可以使用\d*
而不是\d+?
。
import os
import re
dump_key = 20171112003450
backup_files = os.listdir('/home/jadhavy/backup/')
segment_file_regex = "gp_dump_\d+?_\d+?_%s$" %dump_key
for file in backup_files:
if re.match(segment_file_regex,file,re.S):
print(file)