晚上好,
我對 Python 和 RegEx 很陌生。我有以下句子:
-75.76 Card INSURANCEGrabPay ASIA DIRECT to Paid AM 1:16 100.00 3257 UpAmex Top PM 9:55 300.00 3257 UpAmex Top PM 9:55 -400.00 Card LTDGrabPay PTE AXS to Paid PM 9:57 (SGD) Amount Details Time here. appear will transactions cashless your All 2022 Feb 15 on made transactions GrabPay points 52 earned points Rewards 475.76 SGD spent Amount 0.24 SGD balance Wallet 2022 Feb 15 Summary statement daily your here
我想只搜索“-”以及之后的金額。
之后,如果需要在一個組中,我想跳過 2 個單詞并提取所有單詞(我將閱讀更多關于組的資訊,但現在我需要在一個組中,我以后可以用它來拆分并獲取單詞從那個字串)就在“付費”之前
例如,我會得到
-75.76 ASIA Direct to
-400 PTE AXS to
什么是正則運算式命令?另外,是否有一個很好的正則運算式教程可供我閱讀?
uj5u.com熱心網友回復:
現在我已經創建了一個包含 2 個組的匹配項,即 group1 用于數量,group2 用于所有單詞(也包括“to”字串)。
正則運算式:
(-\d \.?\d ) \w \w ([\w ] )?Paid
您可以在此處查看詳細資訊:https ://regex101.com/r/eUMgdW/1
Python代碼:
import re
output = re.findall("""(-\d \.?\d ) \w \w ([\w ] )?Paid""", your_input_string)
for found in output:
print(found)
#('-75.76', 'ASIA DIRECT to ')
#('-400.00', 'PTE AXS to ')
uj5u.com熱心網友回復:
我不會給你真正的正則運算式,而是輕輕地把你推向正確的方向。這樣更讓人滿足。
這里的“單詞”用空格隔開。因此,您要搜索的是一組字符(捕獲),一個空格,再次字符,空格,字符,空格,然后捕獲所有內容并以“PAID”結尾。嘗試創建一個正則運算式來做到這一點。
如果您想復習正則運算式,請查看Regex101。這是一個測驗正則運算式的網路工具,以及一個除錯器和一個備忘單。
uj5u.com熱心網友回復:
我同意第一個評論者的觀點,但我提供了我的看法,因為這實際上是一個更復雜的例子,你試圖避免使用單詞然后捕獲第二組。這是我有效的即時解決方案:
import re
your_string = "-75.76 Card INSURANCEGrabPay ASIA DIRECT to Paid AM 1:16 100.00 3257 UpAmex Top PM 9:55 300.00 3257 UpAmex Top PM 9:55 -400.00 Card LTDGrabPay PTE AXS to Paid PM 9:57 (SGD) Amount Details Time here. appear will transactions cashless your All 2022 Feb 15 on made transactions GrabPay points 52 earned points Rewards 475.76 SGD spent Amount 0.24 SGD balance Wallet 2022 Feb 15 Summary statement daily your here"
# split the string on "Paid" and then strip whitespace
paid_split_string = [substring.strip() for substring in your_string.split("Paid")]
# find payment amounts last three words before "Paid"
captures = [re.findall(r'-\d.*', substring)[0] for substring in paid_split_string if re.findall(r'-\d.*', substring)]
for capture in captures:
print(capture.split()[0] " " " ".join(capture.split()[3:]))
RegExr是一個了不起的互動式網站,您可以在其中測驗模式,然后查看每個特殊字符的作用。我不能推薦該網站,請收藏它以供參考。如果你有 LinkedIn Learning,我也強烈推薦這門課程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429096.html
