### 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);
}
}```

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.
*/
return false;
}
}```

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

//Invalid ZIP codes

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.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

//Invalid ISBNs

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```