我努力正确格式化正则表达式以提取以下文件名中的第一个日期:
TEST_2022-03-04-05-30-20.csv_parsed.csv_encrypted.csv
我运行了以下命令并希望提取每个文件名中的第一个日期,格式为
2022-03-04
date = re.search(' (\d{4}-\d{2}-\d{2}).', 文件名)
我在 re.search 行上得到以下错误:>AttributeError: 'NoneType' object has no attribute 'group'
下面的答案很有帮助并解决了问题。它是学习如何使用正则表达式搜索的宝贵资源。
你的正则表达式有一些问题。
首先,正则表达式本身是不正确的:
\b # Match a word boundary (non-word character followed by word character or vice versa)
( # followed by a group which consists of
\d{4}- # 4 digits and '-', then
\d{2}- # 2 digits and '-', then
\d{2} # another 2 digits
) # and eventually succeeded by
\. # a dot
由于您的
filename
(TEST_2022-03-04-05-30-20.csv_parsed.csv_encrypted.csv
) 没有任何这样的组,因此 re.search()
失败并返回 None
。原因如下:
2022-03-04
后面没有点\b
不匹配,因为 _
和 2
都被认为是单词字符。话虽这么说,正则表达式应该修改,像这样:
(?<=_) # Match something preceded by '_', which will not be included in our match,
\d{4}- # 4 digits and '-', then
\d{2}- # 2 digits and '-', then
\d{2} # another 2 digits, then
\b # a word boundary
现在,你看到那些反斜杠了吗?永远记住,你需要在字符串中again转义它们。这可以使用原始字符串自动执行:
r'(?<=_)\d{4}-\d{2}-\d{2}\b'
试试看:
filename = 'TEST_2022-03-04-05-30-20.csv_parsed.csv_encrypted.csv'
match = re.search(r'(?<=_)\d{4}-\d{2}-\d{2}\b', filename).group(0)
print(match) # '2022-03-04'
在继续尝试提取匹配的文本之前,您需要检查正则表达式是否匹配。
for filename in filenames:
match = re.search(r'\b(\d{4}-\d{2}-\d{2})\.', filename)
if not match:
continue
date = match.group(1)
...
还要注意使用
r'...'
原始字符串,以及使用 group(1)
仅从括号表达式中提取匹配项。