如何在使用regex.findall时删除逗号?

问题描述 投票:0回答:2

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

((椭圆表示其他文字)。

我想使用正则表达式来查找余额列表,即re.findall(r'Balance: (.*)', txt)

但是我只想返回47124和1234,而不是47124和1,234。显然,我可以在之后替换该字符串,但这似乎遍历了该字符串两次,从而使其运行了两倍的时间。

我希望能够输出无逗号的结果while进行re.findall

python regex string comma nsregularexpression
2个回答
0
投票

尝试使用以下正则表达式模式:

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,然后允许这些相同的值后接一个或多个逗号分隔的千位组。


0
投票

这是在处理每个比赛时进行替换的一种方法,它可能比收集所有比赛然后进行替换的效率稍高:

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

输出:

['47124', '1234']
© www.soinside.com 2019 - 2024. All rights reserved.