繁体   English   中英

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

[英]python re match digits or digits followed by characters

我如何匹配以下字符串:

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

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

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

\b\d+\w*\b

RegEx演示

码:

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']

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

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

您可以在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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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