Home > Mobile >  How to match multiple SSN in one line using Regex
How to match multiple SSN in one line using Regex

Time:03-27

I've string like below with 3 SSN numbers.

Mr Tim Tom SSN 123-45-6789 (United States); alt. SSN 345-45-6576 (United States) SSN 22-1234567-8 (Philippines)

I'm trying to get SSN's using Regex and C#

O/P:
123-45-6789
345-45-6576
22-1234567-8

Or

O/P:
SSN 123-45-6789
SSN 345-45-6576
SSN 22-1234567-8

I'm unable to get all SSN's with below logic

var matches = Regex.Matches("Mr Tim Tom...<<above string>>", "SSN (. )", RegexOptions.Singleline);

Any help please

CodePudding user response:

Try using the regex pattern:

SSN (\d (?:-\d ){2})

C# code:

var input = "Mr Tim Tom SSN 123-45-6789 (United States); alt. SSN 345-45-6576 (United States) SSN 22-1234567-8 (Philippines)";
MatchCollection matches = Regex.Matches(input, @"SSN (\d (?:-\d ){2})");
foreach (Match match in matches)
{
    Console.WriteLine("SSN: {0}", match.Groups[1].Value);
}

This prints:

SSN: 123-45-6789
SSN: 345-45-6576
SSN: 22-1234567-8

CodePudding user response:

That should work:

SSN\s[\d\-]{9,}
SSN             #literal string
   \s           #single whitespace character
     [    ]     #matching group, match any symbol between the brackets
      \d        #match any number
        \-      #match a hyphen, escaped
           {9,} #quantifier, match previous expression between 9 and unlimited times
  • Related