使用正则表达式,我想找出列表中的哪些元素以样式 (yyyy-mm-dd) 结尾,例如 (2016-05-04) 等。模式 r'(2016-\d\d-\d\d)' 看起来不错,即使是天真。将它与 Endswith 结合的正确方法是什么?谢谢你。import rea_list = ["Peter arrived on (2016-05-04)", "Building 4 floor (2020)", "Fox movie (2016-04-04)", "David 2016-08-", "Mary comes late(true)"]style = r'\(2016\-\d\d\-\d\d\)'for a in a_list: if a.endswith(style): print a
3 回答
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
您不能将正则表达式与字符串操作结合使用。只需用于re.search查找匹配并使用$模式中的锚点来检查匹配是否发生在最后
>>> import re
>>> style = re.compile(r'\(2016-\d\d-\d\d\)$')
>>> for a in a_list:
... if style.search(a):
... print (a)
...
Peter arrived on (2016-05-04)
Fox movie (2016-04-04)
千万里不及你
TA贡献1784条经验 获得超9个赞
用 r'\(\d{4}-\d{2}-\d{2}\)$'
前任:
import re
a_list = ["Peter arrived on (2016-05-04)", "Building 4 floor (2020)", "Fox movie (2016-04-04)", "David 2016-08-", "Mary comes late(true)"]
style = r'\(\d{4}-\d{2}-\d{2}\)$'
for a in a_list:
if re.search(style, a):
print a
输出:
Peter arrived on (2016-05-04)
Fox movie (2016-04-04)
添加回答
举报
0/150
提交
取消