JavaBlog.fr / Java.lu DEVELOPMENT,Java Java: Regex Expression checker (Example with Email format)

Java: Regex Expression checker (Example with Email format)

A mini-post to expose a simple method to check the Regex expression:

01public static void testExecuteRegex(String regexExpression, String valueToValidate) throws IOException {
02    // Regex
03    Pattern regexPattern = Pattern.compile(regexExpression);
04    boolean valid=false;
05    if(valueToValidate!=null) {
06            Matcher matcher = regexPattern.matcher(valueToValidate);
07            valid=matcher.matches();
08    }else{ // The case of empty Regex expression must be accepted
09            Matcher matcher = regexPattern.matcher("");
10            valid=matcher.matches();
11        }
12        System.out.println("testExecuteRegex("+valueToValidate+")="+valid);
13}

Examples:

01// Regex for email format
02String regexEmail = "([A-Za-z0-9\\.\\_\\-]+[\\.\\_\\-]*[A-Za-z0-9\\.\\_\\-]*)+@([A-Za-z0-9\\.\\_\\-]+[\\.]*[A-Za-z0-9\\.\\_\\-]+)+\\.[A-Za-z]+";
03 
04testExecuteRegex(regexEmail, "email@email.com");
05testExecuteRegex(regexEmail, "em-ail@email.com");
06testExecuteRegex(regexEmail, "em.ail@email.com");
07testExecuteRegex(regexEmail, "em_ail@email.com");
08testExecuteRegex(regexEmail, "d@email.com");
09testExecuteRegex(regexEmail, "_em_ail@email.com");
10testExecuteRegex(regexEmail, "_em_ailemail.com");
11testExecuteRegex(regexEmail, "_em_ail@;email.com");
12testExecuteRegex(regexEmail, "mff13@21f; fff@DD");

The result in the console could be:

1testExecuteRegex(email@email.com)=true
2testExecuteRegex(em-ail@email.com)=true
3testExecuteRegex(em.ail@email.com)=true
4testExecuteRegex(em_ail@email.com)=true
5testExecuteRegex(d@email.com)=true
6testExecuteRegex(_em_ail@email.com)=true
7testExecuteRegex(_em_ailemail.com)=false
8testExecuteRegex(_em_ail@;email.com)=false
9testExecuteRegex(mff13@21f; fff@DD)=false

That’s all!!!

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post