首页 > 解决方案 > RegEx 匹配温度 (°c)

问题描述

我想获得所有温度/温度范围,它们之间有和没有空格。现在,我可以使用以下方法获取它们之间没有空格的那些:

re.findall(r'[0-9°c-]+', text)

在此处输入图像描述

我需要在正则表达式中添加什么,以便我可以正确地获得它们之间有空格的那些?例如50空间°空间C应该被看作一个整体而不是三个部分。

标签: pythonregexregex-lookaroundsregex-groupregex-greedy

解决方案


尝试使用这种模式:

\d+°c(?:\s*-\d+°c)?

示例脚本:

input = "It is 50°c today.  One range is 30°c-40°c and here is another 10°c -20°c"
matches = re.findall(r'\d+°c(?:\s*-\d+°c)?', input)
print(matches)

['50\xc2\xb0c', '30\xc2\xb0c-40\xc2\xb0c', '10\xc2\xb0c -20\xc2\xb0c']

推荐阅读