Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.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,我有一个很长的文本,希望匹配“rate is(\d+\.\d)%”的所有事件,但只希望将组(\d+\.d)作为匹配字符串的列表返回。我该怎么做 我不能只匹配组,因为它也发生在其他上下文中 范例 "I like how the rate is 6.7%. Now the rate is 11.4% profits were down by 5.6%" 在这种情况下,我需要 [6.7, 11.4] 我明白了,我以为findall会返回匹配的整个字符串,而不是组。感谢您的澄清。当然可以,只需将您

我有一个很长的文本,希望匹配“rate is(\d+\.\d)%”的所有事件,但只希望将组(\d+\.d)作为匹配字符串的列表返回。我该怎么做

我不能只匹配组,因为它也发生在其他上下文中

范例

"I like how the rate is 6.7%. Now the rate is 11.4% profits were down by 5.6%"
在这种情况下,我需要

[6.7, 11.4]


我明白了,我以为findall会返回匹配的整个字符串,而不是组。感谢您的澄清。

当然可以,只需将您想要退回的零件分组:

r'the rate is (\d+\.d)%'
因此,请提供足够的上下文以仅匹配您想要返回的内容,并使用捕获组。然后使用
.findall()
方法,该方法将仅包括匹配的捕获组:

>>> re.findall(r'the rate is (\d+\.\d)%', "I like how the rate is 6.7%. Now the rate is 11.4% profits were down by 5.6%")
['6.7', '11.4']

这可以使用
re.findall()
完成

In [94]: s="I like how the rate is 6.7%. Now the rate is 11.4% profits were down
 by 5.6%"

In [95]: re.findall(r'the rate is (\d+\.\d)%', s)
Out[95]: ['6.7', '11.4']