如何使用正则表达式引用特定部分



我有一个Python字符串,其中包含我想使用正则表达式提取的信息。

例:

"The weather is 75 degrees with a humidity of 13%"

我想把"75"和"13"拉出来。 这是我到目前为止在Python中尝试过的方法。

import re
str = "The weather is 75 degrees with a humidity of 13%"
m = re.search("The weather is d+ degrees with a humidity of d+%", str)
matched = m.group()

但是,这显然匹配整个字符串,而不仅仅是我想要的部分。 如何只提取我想要的数字? 我已经研究了反向引用,但它似乎仅适用于正则表达式模式本身。

m = re.search("The weather is (d+) degrees with a humidity of (d+)%", str)
matched = m.groups()

您需要将您想要的内容包装在括号中...

>>> s1 = "The weather is 75 degrees with a humidity of 13%"
>>> m = re.search("The weather is (d+) degrees with a humidity of (d+)%", s1)
>>> m.groups()
('75', '13')

或者只是使用 findall 从任何字符串中获取数字

>>> re.findall("d+",s1)
['75', '13']

也许您想使用命名组?

>>> m = re.search("The weather is (?P<temp>d+) degrees with a humidity of (?P<humidity>d+)%", s1)
>>> m.group('temp')
'75'
>>> m.group('humidity')
'13'

当您想从文本(如数字)中提取类型化数据时,parse 是一个非常有用的库。在许多方面,它是字符串格式的反面。它采用一种模式,并将进行类型转换。

简单来说,它可以让您避免担心正则表达式组等。

>>> s = "The weather is 75 degrees with a humidity of 13%"
>>> parse("The weather is {} degrees with a humidity of {}%", s)
<Result ('75', '13') {}>

Result对象非常易于使用:

>>> r = _
>>> r[0]
'75'

通过指定字段名称和/或类型转换,我们可以做得更好。以下是我们将结果作为整数所需做的一切:

>>> parse("The weather is {:d} degrees with a humidity of {:d}%", s)
<Result (75, 13) {}>

如果我们想使用非索引键,则添加字段名称:

>>> parse("The weather is {temp:d} degrees with a humidity of {humidity:d}%", s)
<Result () {'temp': 75, 'humidity': 13}>
>>> r = _
>>> r['temp']
75

最新更新