String使用特定字符串替换所有美元金额

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

我需要在python中用字符串中的“”标签替换美元金额。这是我到目前为止已经想到的:

这是我的字符串:

s = 'Accounts and current portion of notes receivable, net of allowances of $2,199 and $2,506 at July 2, 2011 and October 2, 2010, respectively'

通过这个正则表达式,我可以正确地找到所有美元金额。

re.findall(r"[\$]{1}[\d,]+\.?\d{0,2}",s)

给我:

['$2,199', '$2,506']

但是,我想用原始字符串中的“”替换美元金额。我怎么做?

预期产量:

'Accounts and current portion of notes receivable, net of allowances of <amount> and <amount> at July 2, 2011 and October 2, 2010, respectively'
python regex replace dollar-sign
2个回答
0
投票

也许

re.sub(r"[\$]{1}[\d,]+\.?\d{0,2}","<amount>",s)

会做你需要的......顺便说一句,如果你只需要一个你没有指定{1},因为这是默认行为


0
投票

您可以使用以下内容进行替换:

s1 = re.sub("\$([\d,]+\.?\d{0,2})", '<amount>', s)
#              ^                ^

s1 = re.sub("\$([\d,]+(?:\.\d{2})?)", '<amount>', s)
#              ^      %         % ^
#  in between '^' matches the entire dollar amount
#  in between '%' matches the decimal part

可能会更好。

括号内的部分是匹配部分,用替换字符串替换。找到美元符号后,我们会抓住以下所有数字和逗号。因此,用插入符号标记的括号之间的内容是被替换的匹配部分。对小数处理部分略有调整。使用您的代码,您可以只匹配'。'或'.5'。上面的版本确保捕获小数点后跟两位数。另请注意,此十进制捕获位于非捕获括号内。但这没关系,因为非捕获括号仍然在捕获括号内。有关详细信息,请参阅https://docs.python.org/3/library/re.html

© www.soinside.com 2019 - 2024. All rights reserved.