Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format ssn using regex

Tags:

c#

regex

asp.net

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 ?

like image 310
john Avatar asked Apr 21 '26 10:04

john


1 Answers

You're using last as a named group in your replacement string without specifying it in your pattern.

Update your pattern as follows and your existing code should work:

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

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:

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

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:

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

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:

string SSN = "123456789";
string formattedSSN = "XXX-XX-" + SSN.Substring(SSN.Length - 4, 4);
like image 63
Ahmad Mageed Avatar answered Apr 23 '26 08:04

Ahmad Mageed