我如何匹配以下字符串:
str1 = "he will be 60 years old today"
str2 = "she turns 79yo today this afternoon"
我希望匹配包含数字或数字的字符串,后面跟着字符(没有空格分隔)。
答案 0 :(得分:2)
您可以使用此正则表达式匹配这些词:
\b\d+\w*\b
<强>代码:强>
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