python重新匹配数字或数字后跟字符

时间:2015-07-15 15:01:43

标签: python regex

我如何匹配以下字符串:

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

我希望匹配包含数字或数字的字符串,后面跟着字符(没有空格分隔)。

3 个答案:

答案 0 :(得分:2)

您可以使用此正则表达式匹配这些词:

\b\d+\w*\b

RegEx Demo

<强>代码:

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)

<强>输出:

[u'60', u'79yo']

答案 1 :(得分:1)

您可以使用[0-9]\w+

>>> re.findall('[0-9]\w+', 'hello my friend kilojoules 99how are you?')
['99how']

答案 2 :(得分:0)

您可以在any()中使用生成器表达式:

any(i.isdigit() or i[0].isdigit() for i in my_str.split())

演示:

>>> str1 = "he will be 60 years old today"
>>> str2 = "she turns 79yo today this afternoon"
>>> str3 = "he will be5  ye48ars old today"
>>> any(i.isdigit() or i[0].isdigit() for i in str1.split())
True
>>> any(i.isdigit() or i[0].isdigit() for i in str2.split())
True
>>> any(i.isdigit() or i[0].isdigit() for i in str3.split())
False