正则表达式提取合理的年月日

img

img



import re
str = input()
pattern = re.compile('\d{2,4}-\d{1,2}-\d{1,2}')
res = pattern.findall(str)
print(res)

我刚学python,还是不知道要怎么把单引号和中括号去掉,百度之后还是不懂。

res不是string,需要遍历打印才行

for i in res:
    print(i)

如果只要第一条:

import re
str = "aaa 2012-01-01 ddd"
pattern = re.compile('\d{2,4}-\d{1,2}-\d{1,2}')
res = pattern.findall(str)
print(res[0])

多条

import re
str = "aaa 2012-01-01 ddd 2023-05-11 ddd"
pattern = re.compile('\d{2,4}-\d{1,2}-\d{1,2}')
res = pattern.findall(str)
for x in res:
    print(x)