A mini-post to expose a simple method to check the Regex expression:
public static void testExecuteRegex(String regexExpression, String valueToValidate) throws IOException { // Regex Pattern regexPattern = Pattern.compile(regexExpression); boolean valid=false; if(valueToValidate!=null) { Matcher matcher = regexPattern.matcher(valueToValidate); valid=matcher.matches(); }else{ // The case of empty Regex expression must be accepted Matcher matcher = regexPattern.matcher(""); valid=matcher.matches(); } System.out.println("testExecuteRegex("+valueToValidate+")="+valid); }
Examples:
// Regex for email format String regexEmail = "([A-Za-z0-9\\.\\_\\-]+[\\.\\_\\-]*[A-Za-z0-9\\.\\_\\-]*)+@([A-Za-z0-9\\.\\_\\-]+[\\.]*[A-Za-z0-9\\.\\_\\-]+)+\\.[A-Za-z]+"; testExecuteRegex(regexEmail, "email@email.com"); testExecuteRegex(regexEmail, "em-ail@email.com"); testExecuteRegex(regexEmail, "em.ail@email.com"); testExecuteRegex(regexEmail, "em_ail@email.com"); testExecuteRegex(regexEmail, "d@email.com"); testExecuteRegex(regexEmail, "_em_ail@email.com"); testExecuteRegex(regexEmail, "_em_ailemail.com"); testExecuteRegex(regexEmail, "_em_ail@;email.com"); testExecuteRegex(regexEmail, "mff13@21f; fff@DD");
The result in the console could be:
testExecuteRegex(email@email.com)=true testExecuteRegex(em-ail@email.com)=true testExecuteRegex(em.ail@email.com)=true testExecuteRegex(em_ail@email.com)=true testExecuteRegex(d@email.com)=true testExecuteRegex(_em_ail@email.com)=true testExecuteRegex(_em_ailemail.com)=false testExecuteRegex(_em_ail@;email.com)=false testExecuteRegex(mff13@21f; fff@DD)=false
That’s all!!!
Huseyin OZVEREN