Python, regex to filter elements endswith a style in a list
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-dd-dd)' 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-dd-dd)'
for a in a_list:
if a.endswith(style):
print a
style = r'(d4-d2-d2)'
3 Answers
3
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
re.search
$
>>> import re
>>> style = re.compile(r'(2016-dd-dd)$')
>>> for a in a_list:
... if style.search(a):
... print (a)
...
Peter arrived on (2016-05-04)
Fox movie (2016-04-04)
Use r'(d4-d2-d2)$'
r'(d4-d2-d2)$'
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'(d4-d2-d2)$'
for a in a_list:
if re.search(style, a):
print a
Output:
Peter arrived on (2016-05-04)
Fox movie (2016-04-04)
thank you for the help! Would you mind I choose another one for the answer, as Sunitha hits in 1 go?
– Mark K
Sep 3 at 6:34
It would be
.*(2016-d2-d2)$
The $ symbol says its at the end
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
style = r'(d4-d2-d2)'
?– Rakesh
Sep 3 at 6:27