繁体   English   中英

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

[英]How to use regex to reference specific parts?

我有一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM