TrevorGoodchild
TrevorGoodchild

Reputation: 1060

How to write multi condition SSN regex in C#

I'm trying to use a regex to obscure when a social security number is submitted through a part of our application. The conditions we're being told to check for are if the SSN is sent over as 123-45-6789 or 123 45 6789 (just looking for 3 (space or dash) 2 digits (space or dash) 3 digits.

What I have so far:

Regex regex = new Regex("\d{3}-\d{2}-\d{4}");

var replacement = regex.Replace(comments, "SSN Hidden");

So I know the regex is close, but incorrect, for dashes and I need help figuring out how to incorporate spaces as well. New to regex, thanks in advance.

Upvotes: 0

Views: 149

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

I suggest using

var replacement = Regex.Replace(comments, @"\d{3}([- ])\d{2}\1\d{4}", "SSN Hidden");

Consider using word boundaries \b around the pattern (@"\b\d{3}([- ])\d{2}\1\d{4}\b") if you need to match these numbers as whole words. Or, use lookarounds to make sure there are no other digits on both ends: @"(?<!\d)\d{3}([- ])\d{2}\1\d{4}(?!\d)".

To make \d only match ASCII digits, consider passing the RegexOptions.ECMAScript option.

Details

  • \d{3} - three digits
  • ([- ]) - Capturing group 1: a space or -
  • \d{2} - two digits
  • \1 - a backreference to Group 1 value (so, it is either - or space)
  • \d{4} - four digits.

See the regex demo.

Upvotes: 1

Related Questions