2

I am trying to mask the SSN which is in "123-12-1234" to "XXX-XX-1234". I am able achieve using the below code.

string input = " 123-12-1234  123-11-1235 ";

Match m = Regex.Match(input, @"((?:\d{3})-(?:\d{2})-(?<token>\d{4}))");

while (m.Success)
{
    if (m.Groups["token"].Length > 0)
    {
        input = input.Replace(m.Groups[0].Value,"XXX-XX-"+ m.Groups["token"].Value);
    }
    m = m.NextMatch();
}

Is there a better way to do it in one line using the Regex.Replace method.

2 Answers 2

5

You can try the following:

string input = " 123-12-1234  123-11-1235";

string pattern = @"(?:\d{3})-(?:\d{2})-(\d{4})";
string result = Regex.Replace(input, pattern, "XXX-XX-$1");

Console.WriteLine(result); // XXX-XX-1234  XXX-XX-1235
0
0

If your are going to be doing a lot of masking you should consider a few whether to use compiled regular expression or not.

Using them will cause a slight delay when the application is first run, but they will run faster subsequently.

Also the choice of static vs instances of the Regex should be considered.

I found the following to be the most efficient

public class SSNFormatter 
{
    private const string IncomingFormat = @"^(\d{3})-(\d{2})-(\d{4})$";
    private const string OutgoingFormat = "xxxx-xx-$3";

    readonly Regex regexCompiled = new Regex(IncomingFormat, RegexOptions.Compiled);

    public string SSNMask(string ssnInput)
    {
        var result = regexCompiled.Replace(ssnInput, OutgoingFormat);
        return result;
    }
}

There is a comparison of six methods for regex checking/masking here.

Not the answer you're looking for? Browse other questions tagged or ask your own question.