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 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With