Skip to main content
 首页 » 编程设计

C# 正则表达式。替换文本中的信用卡

2024年01月22日28lexus

我有一些里面有信用卡号的文本,比如: “您的信用卡号是 4321432143219999,这真的是您的信用卡!”

我需要通过 RegEx 找到这个数字并将其替换为 ************9999,因此结果文本应该是: “您的信用卡号码是 ************9999,这真的是您的信用卡!”

如何在 C# 中实现?

谢谢!

请您参考如下方法:

var str = "Your credit card number is 4321432143219999, this is really your credit card!"; 
var res = Regex.Replace(str, "[0-9](?=[0-9]{4})", "*"); 

这将搜索后跟至少 4 位数字的数字,并将其替换为 *(因此它会被 123456 愚弄,并且会在 **3456)

如果您的信用卡号是 16 位长:

var res2 = Regex.Replace(str, @"\b[0-9]{12}(?=[0-9]{4}\b)", new string('*', 12)); 

这将用 12x * 替换 12 位数字后跟 4 位数字(因此总共 16 位数字)的 block 。数字必须用空格或其他非单词字符与其他文本分开。所以 A1234567890123456 不好,1234567890123456A 也不好。 1234567890123456, 可以,因为 , 是非单词字符。