Regex

Regex for social security number validation

United States Social Security numbers are nine-digit numbers in the format AAA-GG-SSSS with following rules.

  • The first three digits called the area number. The area number cannot be 000, 666, or between 900 and 999.
  • Digits four and five are called the group number and range from 01 to 99.
  • The last four digits are serial numbers from 0001 to 9999.

Regex : ^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$

^            # Assert position at the beginning of the string.
(?!000|666)  # Assert that neither "000" nor "666" can be matched here.
[0-8]        # Match a digit between 0 and 8.
[0-9]{2}     # Match a digit, exactly two times.
-            # Match a literal "-".
(?!00)       # Assert that "00" cannot be matched here.
[0-9]{2}     # Match a digit, exactly two times.
-            # Match a literal "-".
(?!0000)     # Assert that "0000" cannot be matched here.
[0-9]{4}     # Match a digit, exactly four times.
$            # Assert position at the end of the string.

static String regex = "^(?!000|666)[0-8][0-9]{2}-(?!00)[0-9]{2}-(?!0000)[0-9]{4}$";
private static Pattern emailPattern = Pattern.compile(regex);
    
public static Boolean isValidSSNFormat(String ssn) {
        if(ssn==null || ssn.length()==0) {
            return false;
        }
        return emailPattern.matcher(ssn).matches();
}

 

Regex for email validation

public class EmailRegex {
    static String regex = "^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
    private static Pattern emailPattern = Pattern.compile(regex);
    
    public static Boolean isValidEmailFormat(String email) {
        if(email==null || email.length()==0) {
            return false;
        }
        return emailPattern.matcher(email).matches();
    }
}
public class EmailRegexDemo {
    public static void main(String[] args) {
        String email = "folau@gmail.com";
        
        boolean valid = EmailRegex.isValidEmailFormat(email);
        
        System.out.println(email+" is a valid email = "+valid);
    }
}

Regex for password validation

Password validation is the need for almost all the applications today. There are various ways to do validate passwords from writing everything manually to use third party available APIs.

static String regex = "((?=.*[a-z])(?=.*d)(?=.*[@#$%])(?=.*[A-Z]).{6,16})";
  
  /*
   * (?=.*[a-z])     : This matches the presence of at least one lowercase letter.
   * (?=.*d)         : This matches the presence of at least one digit i.e. 0-9.
   * (?=.*[@#$%])    : This matches the presence of at least one special character.
   * ((?=.*[A-Z])    : This matches the presence of at least one capital letter.
   * {6,16}          : This limits the length of password from minimum 6 letters to maximum 16 letters.
   */
  public static Boolean isValidPasswordFormat(String password) {
      if(password==null || password.length()==0) {
          return false;
      }
      return Pattern.compile(regex).matcher(password).matches();
  }

 

US zipcode regex validation 

/*
* ^         # Assert position at the beginning of the string.
* [0-9]{5}  # Match a digit, exactly five times.
* (?:       # Group but don't capture:
* -         # Match a literal "-".
* [0-9]{4}  # Match a digit, exactly four times.
* )         # End the non-capturing group.
* ?         # Make the group optional.
* $         # Assert position at the end of the string.
*/
static String US_ZIPCODE_REGEX = "^[0-9]{5}(?:-[0-9]{4})?$";
public static Boolean isValidUSZipcodeFormat(String zipcode) {
    if(zipcode==null || zipcode.length()==0) {
        return false;
    }
    return Pattern.compile(US_ZIPCODE_REGEX).matcher(zipcode).matches();
}

public class ZipcodeDemo {
    public static void main(String[] args) {
        
        List<String> zips = new ArrayList<String>();
           
        //Valid ZIP codes
        zips.add("12345"); 
        zips.add("12345-6789"); 
         
        //Invalid ZIP codes
        zips.add("123456"); 
        zips.add("1234"); 
        zips.add("12345-678");
         
        zips.add("12345-67890");
         
        for (String zip : zips)
        {
            boolean valid = ZipcodeRegex.isValidUSZipcodeFormat(zip);
            System.out.println(zip+" is a valid US zipcode? "+valid);
        }
         
        
        
    }
}

12345 is a valid US zipcode? true
12345-6789 is a valid US zipcode? true
123456 is a valid US zipcode? false
1234 is a valid US zipcode? false
12345-678 is a valid US zipcode? false
12345-67890 is a valid US zipcode? false

UK zipcode regex validation 

static String UK_ZIPCODE_REGEX = "^[A-Z]{1,2}[0-9R][0-9A-Z]? [0-9][ABD-HJLNP-UW-Z]{2}$";
    
    
public static Boolean isValidUKZipcodeFormat(String zipcode) {
    if(zipcode==null || zipcode.length()==0) {
        return false;
    }
    return Pattern.compile(UK_ZIPCODE_REGEX).matcher(zipcode).matches();
}

Regex for number of lines

StringBuilder line = new StringBuilder();
line.append("Hey man");
line.append("\n");
line.append("I like Java");
line.append("\n");
        
boolean valid = StringRegex.isValidLines(line.toString(), 2);
System.out.println("does \n===\n" + line.toString() + "===\nhas 2 lines? " + valid);

Regex for number of words

public static Boolean isValidLength(String str, int length) {
        String regex = "^\\W*(?:\\w+\\b\\W*){1,"+length+"}$";
        return Pattern.compile(regex).matcher(str).matches();
}
public class StringRegexDemo {
    public static void main(String[] args) {
        List<String> inputs = new ArrayList<String>();
        inputs.add("Folaulau");
        inputs.add("JAVA is great");
        inputs.add("I love java programming");
        
        inputs.forEach((input) -> {
            int length = 10;
            boolean valid = StringRegex.isValidLength(input, length);
            System.out.println("is " + input + " " + length + " in length? " + valid);
        });
    }
}

# output
is Folaulau 10 in length? true
is JAVA is great 10 in length? true
is I love java programming 10 in length? true

Regex for ISBN

ISBN-10 or ISBN-13 : ^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})
[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)
(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$

public class RegexISNBDemo {
    public static void main(String[] args) {
        List<String> isbns = new ArrayList<String>();
           
        //Valid ISBNs
        isbns.add("0-596-52068-9"); 
        isbns.add("0 512 52068 9"); 
        isbns.add("ISBN-10 0-596-52068-9");
        isbns.add("ISBN-10: 0-596-52068-9");
         
        //Invalid ISBNs
        isbns.add("0-5961-52068-9"); 
        isbns.add("11 5122 52068 9"); 
        isbns.add("ISBN-13 0-596-52068-9");
        isbns.add("ISBN-10- 0-596-52068-9");
        
        isbns.forEach((isbn)->{
            boolean valid = RegexISNB.isValidISBNFormat(isbn);
            System.out.println("is "+isbn+" a valid ISBN? "+valid);
        });
    }
}
is 0-596-52068-9 a valid ISBN? true
is 0 512 52068 9 a valid ISBN? true
is ISBN-10 0-596-52068-9 a valid ISBN? true
is ISBN-10: 0-596-52068-9 a valid ISBN? true
is 0-5961-52068-9 a valid ISBN? false
is 11 5122 52068 9 a valid ISBN? false
is ISBN-13 0-596-52068-9 a valid ISBN? true
is ISBN-10- 0-596-52068-9 a valid ISBN? false

Remove special characters from file name

 /*
 * Only alphabets[a-z] and digits[0-9], dot, underscore, dash
 */
String alphaAndDigits = "[^a-zA-Z0-9.-_]+";
String newFileName = fileName.replaceAll(alphaAndDigits, "");


@Test
public void test_replace_invalid_characters() {
    String fileName = "test .jpg";
    String newFileName = FileUtils.replaceInvalidCharacters(fileName);
    System.out.println("newFileName=" + newFileName);
    fileName = "test]&.jpg";
    newFileName = FileUtils.replaceInvalidCharacters(fileName);
    System.out.println("newFileName=" + newFileName);
    fileName = "test$.jpg";
    newFileName = FileUtils.replaceInvalidCharacters(fileName);
    System.out.println("newFileName=" + newFileName);
    fileName = "test@=`.jpg";
    newFileName = FileUtils.replaceInvalidCharacters(fileName);
    System.out.println("newFileName=" + newFileName);
}
newFileName=test.jpg
newFileName=test.jpg
newFileName=test.jpg
newFileName=test.jpg

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *