Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找下划线和句点后的日期格式的正则表达式_Python_Regex - Fatal编程技术网

Python 查找下划线和句点后的日期格式的正则表达式

Python 查找下划线和句点后的日期格式的正则表达式,python,regex,Python,Regex,我有一个文件列表,其中一些是备份,我需要忽略格式化的备份 .2018-12-22或_2019-12-18。 我相信Regex是我最好的选择,但我没有什么经验 我尝试过使用正则表达式,但似乎无法使格式接受文件名后日期之前的句点或下划线 file_list=(glob.glob("/home/test/testdir")) date1= date2= backups=[date1, date2] for file in listoffiles: exists = os.path.isfil

我有一个文件列表,其中一些是备份,我需要忽略格式化的备份 .2018-12-22或_2019-12-18。 我相信Regex是我最好的选择,但我没有什么经验

我尝试过使用正则表达式,但似乎无法使格式接受文件名后日期之前的句点或下划线

file_list=(glob.glob("/home/test/testdir"))
date1=
date2=
backups=[date1, date2]

for file in listoffiles:
    exists = os.path.isfile(file)
    if exists:
        for i in backups:
            ignore = i in file 

如果存在备份文件,则应忽略这些文件。

re.search
。让我们举两个例子:

import re
string1 = 'abc.2018-12-22 ghi'
string2 = ' or _2019-12-18.2929'

re.search('(\.|_)(\d{4}-\d{2}-\d{2})', string1).group(2)
re.search('(\.|_)(\d{4}-\d{2}-\d{2})', string2).group(2)
输出: 说明:
re.search
查找可提取的匹配组。每组都用括号括起来。让我们分解正则表达式
(\.||)(\d{4}-\d{2}-\d{2})

(\.\124;)
:查找
字符。(
\
是转义字符,它允许您将
用作字符,而不是其正则表达式的含义)。这是第一组


(\d{4}-\d{2}-\d{2})
:然后,找到4个数字,一个破折号,2个数字,一个破折号和2个数字。因为它也包含在括号中,这是第2组和您感兴趣的组,这就是为什么我们将
group(2)
添加到
re.search

您可以执行以下操作:

重新导入
备份=[“2018-12-22”、“2018-12-23”、“2019/23/14”、“2019-23-14”、“2019-12-23”]
忽略_regex=re.compile(r“[|.]\d{4}-\d{2}-\d{2}”)
对于备份中的i:
ignore=如果ignore_regex.match(i)else为False,则为True
打印(i,忽略)
结果:

2018-12-22错误
_2018-12-23真实
2019/23/14假
.2019-23-14真实
2019-12-23假
编辑1
ignore_regex=re.compile(r“auto[|.]\d{4}-\d{2}-\d{2}”)

这就是我要找的!不过我有个问题,如果我有其他扩展名,比如.bak或.old,我可以循环使用这些扩展名以及ignore_regex来检查重复的文件吗?请您添加更多详细信息,您所说的扩展名:您是指像这样的“date.back”吗?是的,我很抱歉,一些文件的格式如下:auto.misc,auto.bak,例如,auto.2019-02-25或auto_2019-02-25。该示例中唯一不应忽略的文件是auto。misc@WillMccurry我的awser已更新,请告诉我是否适合您。点击check(检查)按钮即可验证awnser。
'2018-12-22'
'2019-12-18'