我正在嘗試在 python 中使用惰性正則運算式模式來獲取指定單詞之后的第一個數字,在本例中為非 GAAP。但是我只想要至少有 2 位或更多小數位的數字。
這是我的字串:
s = 'Non-GAAP-2 net income of with EPS of 1.21, up 23% from the fourth quarter of 2020.'
我的模式是:
\bNon.*GAAP\b.*?\b(\d (?:\.\d )?)\b
這與非 GAAP 之后的數字 2 匹配,而實際上我想要數字 1.21。
我該如何解決這種模式,你能解釋一下邏輯嗎?
謝謝。
uj5u.com熱心網友回復:
為此使用 re
import re
s = 'Non-GAAP-2 net income of with EPS of 1.21, up 23% from the fourth quarter of 2020.'
output = re.sub(r'\d \.\d ', '', s)
uj5u.com熱心網友回復:
你可能需要:
\bNon-GAAP\b.*?\b(\d \.\d{2,})\b
查看在線演示
\bNon-GAAP\b- 字邊界之間的文字字串“Non-GAAP”;.*?- 除換行符以外的 0 (懶惰)字符;\b(\d \.\d{2,})\b- 1 個以上數字的捕獲組,后跟一個文字點和至少兩個數字,位于單詞邊界之間。
使用這個 re.findall()
import re
s = 'Non-GAAP-2 net income of with EPS of 1.21, up 23% from the fourth quarter of 2020.'
print(float(re.findall(r'\bNon-GAAP\b.*?\b(\d \.\d{2,})\b', s)[0]))
印刷:
1.21
uj5u.com熱心網友回復:
您可以使用\d*\.\d*which 將捕獲字串中帶小數位的第一個數字
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409271.html
標籤:
