从字符串中提取温度(摄氏度或华氏度) [英] extracting temperature degrees (celcius or fahrenheit) from string
问题描述
我正在使用 (char.*?char2)
来提取以 char1
开头并以 char2
结尾的子部分字符串.
I am using (char.*?char2)
in order to extract subparts which starts with char1
and which ends with char2
from a string.
现在我想提取温度信息,例如(40 °C, -30°C, 80°F) 从字符串.在这种情况下,我的正则表达式应该通过考虑 +
和 -
的概率来定义任何数字字符的开头字符,以及以 °C结尾的字符code> 或
°F
,并且中间不能有任何字母,并且数字和结尾之间也应该有 whitespace
字符.
Now I want to extract temperature information e.g. (40 °C, -30°C, 80°F) from a string. In this case my regex expression should define the beginning character with any digit characters by taking into the probability of +
and -
, and the ending with °C
or °F
, and there shouldn't be any letter in between, and it should also take whitespace
character between the number and ending into possibility.
如何定义这样的正则表达式?
How can I define such a regex?
我已经检查过了,正则表达式提取温度和温度范围从一个字符串,但答案的目标略有不同.
I have checked this, Regex to extract temperatures and temperature ranges from a string, but the answer has slightly a different goal.
推荐答案
(\d+) ?°([CF])
第一组应该有温度,第二组应该是 C 或 F.
The first group should have the temperature, the second C or F.
扩展它以允许更多变化:
Expanding it to allow for a bit more variation:
([+-]?\d+(\.\d+)*)\s?°([CcFf])
这将匹配任何这些输入,允许多个空格或制表符、小写单位, 小数点和符号.
This would match any of these inputs, allowing for more than one space, or tab, lower case unit, decimal points and signs.
示例python程序:
Example python program:
import re
string = '''
20°C
2 °F
It was cold, 2 °F in fact.
30 °C
-40 °C
+2.3^I°c
+2.3°c
10°C
'''
pattern = r'([+-]?\d+(\.\d+)*)\s?°([CcFf])'
print(re.findall(pattern, string))
# Output:
# [('20', '', 'C'), ('2', '', 'F'), ('2', '', 'F'), ('30', '', 'C'),
# ('-40', '', 'C'), ('+2.3', '.3', 'c'), ('+2.3', '.3', 'c'),
# ('10', '', 'C')]
这篇关于从字符串中提取温度(摄氏度或华氏度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!