Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re match digits or digits followed by characters

Tags:

python

regex

How would I match the following strings:

str1 = "he will be 60 years old today"
str2 = "she turns 79yo today this afternoon"

I want to match strings that contain a digit or digit immediately followed by characters (no whitespace separated).

like image 854
user1879926 Avatar asked Mar 06 '26 16:03

user1879926


1 Answers

You can use this regex to match those words:

\b\d+\w*\b

RegEx Demo

Code:

import re
p = re.compile(ur'\b\d+\w*\b')
test_str = u"he will be 60 years old today\nshe turns 79yo today this afternoon"

print re.findall(p, test_str)

Output:

[u'60', u'79yo']
like image 141
anubhava Avatar answered Mar 08 '26 04:03

anubhava