[英]Regex how to search more than one digits in a phrase
我有一个包含短语+温度的字符串数据集:
前任。 string = "纽约潮湿,气温为 15.43C"。 only_temp="15.43C"
我的代码: -->If only_temp="15.43C" 那么
re.search('\d+.\d\dC', string)
找到它。
-->如果“纽约潮湿,气温为 15.43C” 。
re.search("(.*)(\d+.\d\dC)", string)
找到“纽约潮湿”和“5.43C”的2组。 (而不是 15.43C)
我相信问题出在。*但我找不到解决方案。
在
re.search("(.*)(\d+.\d\dC)",string)
'(.*)'
贪婪地捕捉任何东西。 以下'(\d+.\d\dC)'
也贪婪地捕获 - 但它只在点之前强制执行 1+ 位。 这就是第一个表达式捕获1
的原因。
让它不贪婪:
re.search("(.*?)(\d+.\d\dC)",string)
所以第一个表达式只捕获lazy / he 至少它必须。 然后后续将捕获全摄氏度。 如果您根本不需要它,您也可以进行第一个非捕获:
re.search("(?:.*?)(\d+.\d\dC)",string)
演示:
import re
string = "New York is humid with 15.43C"
only_temp ="15.43C"
s = re.search("(?:.*?)(\d+.\d\dC)", string)
print(s.groups())
Output:
('15.43C',)
我认为你可以简单地使用你的正则表达式:
import re
s = 'New York is humid with 15.43C'
re.search("([\d\.]+C$)", s).groups()
OUTPUT
('15.43C',)
虽然[\d\.]+
确实比\d+.\d\d
更自由的形式- 我认为假设数字和点的组合表示温度是相当安全的。
例如,如果你的句子是这样的:
s = 'New York is humid with 16C'
更严格的模式不会返回任何匹配项。
在任何情况下,请注意点需要转义 - 考虑到 regex .
表示任何字符,否则:
s = "New York is humid with 15A43C"
re.search("(?:.*?)(\d+.\d\dC)", s).groups()
将返回匹配
OUTPUT
('15A43C',)
我确实理解假设\d+.\d\dC
通常会匹配摄氏温度是合理且合理的安全 - 我只是说你不匹配一个点,如果这是意图的话。
您的正则表达式中有几个错误:
.
将匹配任何字符,而不是句点,使用\.
匹配小数点分隔符s = 'New York is humid with 15.43C'
m = re.search('(.*?)\s*(\d+\.\d{,2}C)', s)
m.groups()
# ('New York is humid with', '15.43C')
如果要处理没有小数部分的情况:
s = 'New York is humid with 15C'
m = re.search('(.*?)\s*(\d+(?:\.\d{,2})?C)', s)
m.groups()
# ('New York is humid with', '15C')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.