用python正则表达式从字符串中捕获单词

时间:2017-04-16 04:12:35

标签: python regex

我试图从字符串中捕获月数。所以我想要的是2或2。我做了:

s = '2 month free two month free'
re.findall(r'(\d|\w) month free',s)

我得到的是['2', 'o']。似乎我无法捕获整个单词' two'。谁能知道为什么?非常感谢。

2 个答案:

答案 0 :(得分:1)

您只需在+后添加加号\w即可匹配整个号码。

s = '2 month free two month free'
re.findall(r'(\d|\w+) month free',s)

输出:

['2', 'two']

答案 1 :(得分:1)

您需要添加+以指定一个或多个字符

import re
s = '2 month free two month free'
print(re.findall(r'(\d+|\w+) month free',s))

输出:

['2', 'two']