[英]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.