Thursday 21 December 2017

How to write regex for Social Security Number(SSN) | Java Regex | Regex in java


Click here to watch on Youtube :
https://www.youtube.com/watch?v=A2Vm-hS51u8&list=UUhwKlOVR041tngjerWxVccw

RegexDemo.java

import java.util.ArrayList;
import java.util.List;

/**
 *
 * A Social Security Number (SSN) consists of nine digits, commonly written as
 * three fields separated by hyphens: AAA-GG-SSSS.
 *
 * The first three-digit field is called the "area number".
 * The central, two-digit field is called the group number".
 * The final, four-digit field is called the "serial number"
 *
 */

public class RegexDemo
{

    public static void main(String[] args)
    {
        List<String> ssnList = new ArrayList<String>();
        ssnList.add("123-45-6789");
        ssnList.add("9876-5-4321");
        ssnList.add("987-65-4321 (G)");
        ssnList.add("987-65-4321");
        ssnList.add("192-83-7465");

        String ssnRegex = "^(\\d{3}-\\d{2}-\\d{4})"; 
     
        for (String ssn : ssnList)
        {
            if (ssn.matches(ssnRegex))
            {
                System.out.println("Found good SSN: " + ssn);
            }
        }
    }

}

Output

Found good SSN: 123-45-6789
Found good SSN: 987-65-4321
Found good SSN: 192-83-7465

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/RegexDemo_SSN.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/RegexDemo_SSN

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/576579fab6c376d5ecd7cb5b7402b7fd1a7c4ae3/BasicJava/RegexDemo_SSN/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • 1 comment: