我有一个很长的文本,想要匹配“速率是(\ 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会返回匹配的整个字符串,而不是组。谢谢你的澄清。
答案 0 :(得分:1)
当然可以,只需将您要退回的部分分组:
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']
答案 1 :(得分:1)
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']
答案 2 :(得分:-1)
可以使用re.findall()
完成此操作。