Hi I need regex in c sharp to display SSN in the format of xxx-xx-6789. i.e 123456789 should be displayed as xxx-xx-6789 in a textfield. The code I am using write now is
string SSN = "123456789";
Regex ssnRegex = new Regex("(?:[0-9]{3})(?:[0-9]{2})(?:[0-9]{4})");
string formattedSSN = ssnRegex.Replace(SSN, "XXX-XX-${last}");
What is correct Reg Expression to mask ssn xxx-xx-6789 ?
You’re using
lastas a named group in your replacement string without specifying it in your pattern.Update your pattern as follows and your existing code should work:
Depending on your input you may want to restrict the pattern to match the entire input by using the
^and$metacharacters to match the start and end of the string, respectively. By doing so the regex won’t match an input with more than 9 consecutive numbers. This would look like:Also, since all you care about is the last 4 digits, you might choose to match 5 numbers, followed by 4 numbers, instead of splitting it up into 3 groups:
In addition, if your input is always 9 numbers and can be trusted, then regex is not needed. You could simply get the substring to extract the last 4 characters: