簡體   English   中英

如何在使用 regex.findall 時刪除逗號?

[英]How can I remove commas while using regex.findall?

假設我有以下字符串: txt = "Balance: 47,124, age, ... Balance: 1,234..."

(省略號表示其他文本)。

我想使用正則表達式來查找余額列表,即re.findall(r'Balance: (.*)', txt)

但我只想返回 47124 和 1234 而不是 47,124 和 1,234。 顯然我可以在之后替換字符串,但這似乎是遍歷字符串兩次,從而使運行時間增加一倍。

我希望能夠執行re.findall時獲得 output 無逗號結果。

嘗試使用以下正則表達式模式:

Balance: (\d{1,3}(?:,\d{3})*)

這將僅匹配以逗號分隔的余額金額,並且不會獲取其他任何內容。 示例腳本:

txt = "Balance: 47,124, age, ... Balance: 1,234, age ... Balance: 123, age"
amounts = re.findall(r'Balance: (\d{1,3}(?:,\d{3})*)', txt)
amounts = [a.replace(',', '') for a in amounts]
print(amounts)

['47124', '1234', '123']

以下是正則表達式模式的工作原理:

\d{1,3}      match an initial 1 to 3 digits
(?:,\d{3})*  followed by `(,ddd)` zero or more times

因此該模式匹配 1 到 999,然后允許這些相同的值后跟一個或多個逗號分隔的千位組。

這是一種在處理每個匹配項時進行替換的方法,這可能比收集所有匹配項然后進行替換更有效:

txt = "Balance: 47,124, age, ... Balance: 1,234 ..."
balances = [bal.group(1).replace(',', '') for bal in re.finditer(r'Balance: ([\d,]+)', txt)]
print (balances)

Output:

['47124', '1234']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM