使用RE保护python中的信用卡号码

时间:2015-06-10 10:26:50

标签: python regex

我试图通过用星号屏蔽中间的4位数来屏蔽信用卡号码。我试图在python中使用RE来解决这个问题。

5415********4935

虽然我已经想出如何做到这一点。输出为我提供了一系列没有任何逗号的信用卡号

['5415********4935\r\n5275********9664\r\n5206********3509\r\n5332********3074\r\n5204********2617']

我需要在哪里更改代码才能获得以下输出

['5415********4935,5275********9664,5206********3509,5332********3074,5204********2617']

我的示例代码:

import re,pyperclip

CreditRegex = re.compile(r'''(
(\d{4})
(\s*|\-*)
(\d{4})
(\s*|\-*)
(\d{4})
(\s*|\-*)
(\d{4})

)''',re.VERBOSE)

text = str(pyperclip.paste())
matches=[]

for groups in [CreditRegex.sub(r'\2********\8',text)]:

    groups.rstrip()
    matches.append(groups)

print(matches)

4 个答案:

答案 0 :(得分:1)

您可以使用str.replace()功能

>>> lst = ['5415********4935\r\n5275********9664\r\n5206********3509\r\n5332********3074\r\n5204********2617']

>>> [ lst[0].replace('\r\n', ',') ]
['5415********4935,5275********9664,5206********3509,5332********3074,5204********2617']

答案 1 :(得分:0)

import re,pyperclip

CreditRegex = re.compile(r'''(
(\d{4})
(\s*|\-*)
(\d{4})
(\s*|\-*)
(\d{4})
(\s*|\-*)
(\d{4})

)''',re.VERBOSE)

text = str(pyperclip.paste())
matches=[]

for groups in [CreditRegex.sub(r'\2********\8',text)]:

    groups.rstrip()
    matches.append(groups)

print matches

从打印中删除()。

答案 2 :(得分:0)

使用替换的最简单方法:

x = ['5415********4935\r\n5275********9664\r\n5206********3509\r\n5332********3074\r\n5204********2617']
x[0] = x[0].replace("\r\n",',')
print x
#prints ['5415********4935,5275********9664,5206********3509,5332********3074,5204********2617']

答案 3 :(得分:0)

我真的不明白这里需要正则表达式。

import pyperclip

out = [
    '{}********{}'.format(num[:4], num[8:])
    for num in str(pyperclip.paste()).splitlines()
]
print out

如您所见,您所需要的只是标准字符串操作 我觉得使用列表理解很方便,但这是一个不同的故事。