Validate email in Java using Regex

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static String pattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; private static Pattern mypattern = Pattern.compile(pattern); public static void main( String args[] ){ String valEmail1 = "testemail@domain.com"; String invalEmail1 = "....@domain.com"; String invalEmail2 = ".$$%%@domain.com"; String valEmail2 = "test.email@domain.com"; System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail1)); System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail1)); System.out.println("Is Email ID1 valid? "+validateEMailID(invalEmail2)); System.out.println("Is Email ID1 valid? "+validateEMailID(valEmail2)); } public static boolean validateEMailID(String emailID) { Matcher mtch = mypattern.matcher(emailID); if(mtch.matches()){ return true; } return false; } }
Simple snippet showing the usage o Regex in Java to validate an email address.

#java #email #regex #validation

#cesarnog

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.