仅返回正则表达式中的分组结果

0 投票
3 回答
2743 浏览
提问于 2025-04-17 16:52

我有一段很长的文本,想要找到所有出现的“the 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会返回整个匹配的字符串,而不是只返回那部分。谢谢你的解释。

3 个回答

-1

这可以通过使用 re.findall() 来实现。

你可以查看 7.2. re — 正则表达式操作 了解更多信息。

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答