A mini-post to expose a simple method to check the Regex expression:
01 | public 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 |
02 | String regexEmail = "([A-Za-z0-9\\.\\_\\-]+[\\.\\_\\-]*[A-Za-z0-9\\.\\_\\-]*)+@([A-Za-z0-9\\.\\_\\-]+[\\.]*[A-Za-z0-9\\.\\_\\-]+)+\\.[A-Za-z]+" ; |
03 |
04 | testExecuteRegex(regexEmail, "email@email.com" ); |
05 | testExecuteRegex(regexEmail, "em-ail@email.com" ); |
06 | testExecuteRegex(regexEmail, "em.ail@email.com" ); |
07 | testExecuteRegex(regexEmail, "em_ail@email.com" ); |
08 | testExecuteRegex(regexEmail, "d@email.com" ); |
09 | testExecuteRegex(regexEmail, "_em_ail@email.com" ); |
10 | testExecuteRegex(regexEmail, "_em_ailemail.com" ); |
11 | testExecuteRegex(regexEmail, "_em_ail@;email.com" ); |
12 | testExecuteRegex(regexEmail, "mff13@21f; fff@DD" ); |
The result in the console could be:
1 | testExecuteRegex(email@email.com)=true |
2 | testExecuteRegex(em-ail@email.com)=true |
3 | testExecuteRegex(em.ail@email.com)=true |
4 | testExecuteRegex(em_ail@email.com)=true |
5 | testExecuteRegex(d@email.com)=true |
6 | testExecuteRegex(_em_ail@email.com)=true |
7 | testExecuteRegex(_em_ailemail.com)=false |
8 | testExecuteRegex(_em_ail@;email.com)=false |
9 | testExecuteRegex(mff13@21f; fff@DD)=false |
That’s all!!!
Huseyin OZVEREN