C#RegEx。用文字替换信用卡

时间:2012-03-14 11:28:33

标签: c# asp.net regex replace

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

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

我怎样才能在C#中做到?

谢谢!

2 个答案:

答案 0 :(得分:4)

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中更改< / p>

如果您的信用卡号码长度为16位数:

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

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

答案 1 :(得分:3)

尽可能避免使用正则表达式是最好的,因为它们比普通的子字符串操作更慢,更难以排除故障。

    public static string HideNumber(string number)
    {
        string hiddenString = number.Substring(number.Length - 4).PadLeft(number.Length, '*');
        return hiddenString;
    }