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

2024-03-28 22:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

(省略号表示其他文本)。你知道吗

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

但我只想返回47124和1234,而不是47124和1234。 很明显,我可以在以后替换字符串,但这看起来像是对字符串进行两次迭代,从而使运行时间延长两倍。你知道吗

我希望在执行re.findall时能够输出无逗号的结果。你知道吗


Tags: 字符串文本retxt列表age时间regex
2条回答

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

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']

下面是regex模式的工作原理:

\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)

输出:

['47124', '1234']

相关问题 更多 >