用re.sub()部分替换

时间:2013-05-01 22:36:43

标签: python regex

假设我想在“文本”中找到所有信用卡号,并用XXXX替换前三个4位数组,将最后一组保留原样。

如何使用re.sub()?

执行此操作

到目前为止,我最好的尝试是

re.sub(r"(\d{4}-){3}", "XXXX-XXXX-XXXX-", text)

但当然这种模式会导致替换非信用卡表达,例如'1234-5678-1234-asdfg'。

2 个答案:

答案 0 :(得分:6)

你可以使用先行断言:

re.sub(r"(\d{4}-){3}(?=\d{4})", "XXXX-XXXX-XXXX-", text)

E.g:

In [1]: import re

In [2]: text = '1234-5678-9101-1213 1415-1617-1819-hello'

In [3]: re.sub(r"(\d{4}-){3}(?=\d{4})", "XXXX-XXXX-XXXX-", text)
Out[3]: 'XXXX-XXXX-XXXX-1213 1415-1617-1819-hello'

虽然这也符合asdf1234-4567-1234-4567-asdf。

答案 1 :(得分:3)

使用反向引用的另一种方式:

data = "4220-1234-9948-2245 is a cc num i have and so is 4153-4222-3942-4852 but dont tell anyone"
print re.sub(r"(\d{4}-){3}(\d{4})", "XXXX-XXXX-XXXX-\\2", data)

# XXXX-XXXX-XXXX-2245 is a cc num i have and so is XXXX-XXXX-XXXX-4852 but dont tell anyone
相关问题