Regex for validating domain name

There may be more usecases but that’s not point of discussion here. to List emails = new Array List(); emails.add("[email protected]domain.com"); emails.add("[email protected]"); emails.add("[email protected]domain.com"); emails.add("user.name@domain.com"); emails.add("user#@in"); emails.add("[email protected]domaincom"); //Invalid emails emails.add("user#domain.com"); emails.add("@yahoo.com"); String regex = "^(. )$"; Pattern pattern = Pattern.compile(regex); for(String email : emails) In this regex, we have added some restrictions on username part of email address. :[a-z A-Z0-9-] \.) [a-z A-Z]$"; Pattern pattern = Pattern.compile(regex); for(String email : emails) [email protected]: true [email protected] : true user.name@: true [email protected]: true [email protected]: true [email protected]: false [email protected]

Restrictions in above regex are:1) A-Z characters allowed 2) a-z characters allowed 3) 0-9 numbers allowed 4) Additionally email may contain only dot(.), dash(-) and underscore(_) 5) Rest all characters are not allowed Let’s test some email addresses against above regex. : false [email protected]: false [email protected] : false [email protected] : false This last regex is my recommendation for simple email validation in java.

The side bar includes a Cheatsheet, full Reference, and Help.

Visit Stack Exchange I created this regex in Javascript that returns a boolean for Domain validation that meets the criteria to allow IP addresses and ascii domain name.

The assumption is that the TLD should be atleast two letters.

List emails = new Array List(); emails.add("[email protected]domain.com"); emails.add("[email protected]"); emails.add("[email protected]domain.com"); emails.add("user.name@domain.com"); emails.add("[email protected]"); emails.add("user-name@in"); emails.add("[email protected]domaincom"); //Invalid emails emails.add("@yahoo.com"); String regex = "^[A-Za-z0-9 _.-] @(. Please note that email validation in java without regular expression may be possible, but it is not recommended.

)$"; Pattern pattern = Pattern.compile(regex); for(String email : emails) [email protected]: true [email protected] : true [email protected]: true user.name@: true [email protected] : true user-name@in : true [email protected]domaincom : true @: false This regex example uses all the characters permitted by RFC 5322, which governs the email message format. :\.[a-z A-Z0-9-] )*$"; Pattern pattern = Pattern.compile(regex); for(String email : emails) Now lets modify the regex such that domain name must include at least one dot, and that the part of the domain name after the last dot can only consist of letters. The top-level domain (in these examples) must consist of two to six letters only. Anywhere you need to deal with patterns, regular expressions are your friend.

Leave a Reply