Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python正则表达式从字符串捕获单词_Python_Regex - Fatal编程技术网

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