使用正则表达式格式化ssn

时间:2011-03-10 00:43:21

标签: c# asp.net regex

嗨我需要c锐利的正则表达式以xxx-xx-6789的格式显示SSN。即123456789应在文本字段中显示为xxx-xx-6789。我现在使用的代码是

string SSN = "123456789";
Regex ssnRegex = new Regex("(?:[0-9]{3})(?:[0-9]{2})(?:[0-9]{4})");
string formattedSSN = ssnRegex.Replace(SSN, "XXX-XX-${last}");

什么是正确的Reg表达式来屏蔽ssn xxx-xx-6789?

4 个答案:

答案 0 :(得分:4)

您在替换字符串中使用last作为命名组,而未在模式中指定它。

按如下方式更新您的模式,您的现有代码应该有效:

(?:[0-9]{3})(?:[0-9]{2})(?<last>[0-9]{4})

根据您的输入,您可能希望通过使用^$元字符分别匹配字符串的开头和结尾来限制模式以匹配整个输入。通过这样做,正则表达式将不会匹配超过9个连续数字的输入。这看起来像是:

^(?:[0-9]{3})(?:[0-9]{2})(?<last>[0-9]{4})$

此外,由于你所关心的只是最后4位数字,你可以选择匹配5个数字,然后是4个数字,而不是将它分成3组:

^(?:[0-9]{5})(?<last>[0-9]{4})$

此外,如果您的输入始终是9个数字且可以信任,则不需要正则表达式。您可以简单地获取子字符串以提取最后4个字符:

string SSN = "123456789";
string formattedSSN = "XXX-XX-" + SSN.Substring(SSN.Length - 4, 4);

答案 1 :(得分:1)

SSN Masking的通用代码。

    string originalSSN = Convert.ToString("123-456-789").PadLeft(9, '0');
        int maskDigit = 6;
        string maskSSN = originalSSN.Substring(originalSSN.Length - maskDigit, maskDigit);            
        if (Regex.IsMatch(maskSSN, "(—)|(–)|(-)"))
        {
            int i = maskDigit;
            while (Regex.Replace(maskSSN, "(—)|(–)|(-)", "").Length < maskDigit)
            {
                i++;
                maskSSN = originalSSN.Substring(originalSSN.Length - i, i);
            }

            string[] ssnArray = Regex.Split(maskSSN, "(—)|(–)|(-)", RegexOptions.ExplicitCapture);
            if (ssnArray.Length > 1)
            {
                maskSSN = originalSSN.Substring(originalSSN.Length - maskDigit - (ssnArray.Length - 1), maskDigit + (ssnArray.Length - 1));
            }

        }


        maskSSN = maskSSN.PadLeft(9, '#');

答案 2 :(得分:1)

这个很好的小功能如何掩盖Tins和Ssns:

public static string MaskSSN(string originalSSN)
    {
        if (originalSSN.Length < 5) return originalSSN;
        var trailingNumbers = originalSSN.Substring(originalSSN.Length - 4);
        var leadingNumbers = originalSSN.Substring(0, originalSSN.Length - 4);
        var maskedLeadingNumbers = Regex.Replace(leadingNumbers, @"[0-9]", "X");
        return maskedLeadingNumbers + trailingNumbers;
    }

所以&#34; 123-45-6789&#34;成为&#34; XXX-XX-6789&#34; 和&#34; 12-1234567&#34;成为&#34; XX-XXX4567&#34;。

答案 3 :(得分:0)

string originalSSN = Convert.ToString("123-456-789").PadLeft(9, '0');
int maskDigit = 6;
string maskSSN = originalSSN.Substring(originalSSN.Length - maskDigit, maskDigit);            
if (Regex.IsMatch(maskSSN, "(—)|(–)|(-)")) {
    int i = maskDigit;
    while (Regex.Replace(maskSSN, "(—)|(–)|(-)", "").Length < maskDigit) {
        i++;
        maskSSN = originalSSN.Substring(originalSSN.Length - i, i);
    }

    string[] ssnArray = Regex.Split(maskSSN, "(—)|(–)|(-)", RegexOptions.ExplicitCapture);
    if (ssnArray.Length > 1) {
        maskSSN = originalSSN.Substring(originalSSN.Length - maskDigit - (ssnArray.Length - 1), maskDigit + (ssnArray.Length - 1));
    }
}

maskSSN = maskSSN.PadLeft(9, '#');