使用正则表达式,我想找出列表中的哪些元素,以样式(yyyy-mm-dd)结尾,例如(2016-05-04)等。
模式r'(2016- \ d \ d- \ d \ d)'看起来还算天真。将它与Endswith结合的正确方法是什么?
谢谢。
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'\(2016\-\d\d\-\d\d\)'
for a in a_list:
if a.endswith(style):
print a
答案 0 :(得分: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)
答案 1 :(得分:1)
使用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)
答案 2 :(得分:1)
应该是
.*\(2016\-\d{2}\-\d{2}\)$
$符号在末尾显示