使用python正则表达式从字符串捕获单词
我试图从字符串中获取月数。所以我想要的是两个或两个。我做到了:使用python正则表达式从字符串捕获单词,python,regex,Python,Regex,我试图从字符串中获取月数。所以我想要的是两个或两个。我做到了: s = '2 month free two month free' re.findall(r'(\d|\w) month free',s) 我得到的是['2','o']。似乎我没能抓住“二”这个词的全部含义。有人知道为什么吗?非常感谢 您只需在\w之后添加加号+即可匹配整数 s = '2 month free two month free' re.findall(r'(\d|\w+) month free',s) 输出: ['2
s = '2 month free two month free'
re.findall(r'(\d|\w) month free',s)
我得到的是
['2','o']
。似乎我没能抓住“二”这个词的全部含义。有人知道为什么吗?非常感谢 您只需在\w
之后添加加号+
即可匹配整数
s = '2 month free two month free'
re.findall(r'(\d|\w+) month free',s)
输出:
['2', 'two']
['2', 'two']
您需要添加
+
以指定有一个或多个字符
import re
s = '2 month free two month free'
print(re.findall(r'(\d+|\w+) month free',s))
输出:
['2', 'two']
['2', 'two']