How to Validate a Social Security Number using Regex in C# ?

If you need to validate a social security number in C# , the regular expressions is one of the easy wat to do it .

Below is a sample code snippet demonstrating how to validate a social security number using regular expression .

The pattern for matching it is that SSN number contains nine digits grouped with hypen as option.

How to Validate a Social Security Number using Regex in C# ?

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace AbundantcodeConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
          //  How to Validate a Social Security Number using Regex in C# ?
           string SSNPattern = @"^\d{3}\-?\d{2}\-?\d{4}$";
           Regex regex = new Regex(SSNPattern);
           bool Matching = regex.IsMatch("111-22-45Q6");
           Console.WriteLine(Matching);
           Console.ReadLine();
        }     
    }
    
}
1