Start Validating email addresses using regular expressions

Validating email addresses using regular expressions

The difficult part in the last sentence is the word "probably" because you just can't be sure.

List emails = new Array List(); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("[email protected]"); emails.add("user#@in"); emails.add("[email protected]"); //Invalid emails emails.add(""); emails.add(""); String regex = "^(. )$"; Pattern pattern = Pattern.compile(regex); for(String email : emails) Output: [email protected]: true [email protected] : true [email protected]: true [email protected]: true user#@in : true [email protected] : true user#: false @: false In this regex, we have added some restriction osn username part of email address.

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.

After the code you’ll see the meaning of the regular expression used in the code below. This the regex processor that the email address should start with a word character formed of alphanumeric value (a-z 0-9) or it can also be an hyphen, underscore, dot or a plus symbol.

The second part, symbol means match the preceding zero or more times.

It means that the first characters defined before can be followed with a period "." and after that with the same set of characters than before the period.

Because characters "." and " " have special meaning in regexps they must be escaped with a backslash.

There can be 1..n domain labels separated with a period.

The first label (without the period) is defined by This ugly regexp is actually quite similar to the one declared earlier.

The expression now allows the domain part to end with a period followed by 2..n letters such as These regexps were inspired by and modified from the article "Using Regular Expressions in PHP" by James Ussher-Smith [2].

methods to match a string to be a valid email address based on the given regex.

Author: Markus Sipilä Version: 1.0, 2006-08-02 Permanent URL: address validation is quite a bit more complex than it might sound at first.