Archive
Posts Tagged ‘Validation’
Validating E-mails using Regular Expressions in Java
2012/06/01
2 comments
To sum up the discussion at http://stackoverflow.com/questions/1360113/is-java-regex-thread-safe/, you can reuse (keep in static variables) the compiled Pattern(s) and tell them to give you new Matchers when needed to validate those regex pattens against some string:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Validation helpers
*/
public final class Validators {
private static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*
@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";
private static Pattern email_pattern;
static {
email_pattern = Pattern.compile(EMAIL_PATTERN);
}
/**
* Check if e-mail is valid
*/
public static boolean isValidEmail(String email) {
Matcher matcher = email_pattern.matcher(email);
return matcher.matches();
}
}
(Note: the EMAIL_PATTERN string should be put in a single line)
For the RegEx pattern used, see the article at http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/ and the user comments (and useful links) posted there.
Update (20120715): previous pattern wasn’t accepting “-” in the domain name