简体   繁体   中英

Python, regex to filter elements endswith a style in a list

With regex, I want to find out which of the elements in a list, endswith the style (yyyy-mm-dd), for example (2016-05-04) etc.

The pattern r'(2016-\\d\\d-\\d\\d)' looks alright even tough naive. What's the right way to combine it with Endswith?

Thank you.

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

You cannot combine regex with string operations. Just use re.search to find match and use the anchor $ in your pattern to check if the match happens at the end

>>> 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)

Use r'\\(\\d{4}-\\d{2}-\\d{2}\\)$'

Ex:

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

Output:

Peter arrived on (2016-05-04)
Fox movie (2016-04-04)

It would be

.*\(2016\-\d{2}\-\d{2}\)$

The $ symbol says its at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM