Alex Rivera | Logout

regex for email validation

Asked 2009-02-03T17:34:41.387
14

I have written the regex below for a really simple email validation. I plan to send a confirmation link.

/.*@[a-z0-9.-]*/i

I would, however, like to enhance it from the current state because a string like this does not yield the desired result:

test ,my.name+test@gmail-something.co.uk, test

The "test ," portion is undesirably included in the match. I experimented with word boundaries unsuccessfully.

  1. How should I modify?
  2. Even though I've kept this simple, are there any valid email formats it would exclude?

THANKS!

Edit
Report

1 Answer

-1

A smaller two step regex provides good results

/** check to see if email address is in a valid format. * Leading character of mailbox must be alpha
* remaining characters alphanumeric plus -_ and dot
* domain base must be at least 2 characters
* domain extension must be at least 2, not more than 4 alpha
* Subdomains are permitted. * @version 050208 added apostrophe as valid char * @version 04/25/07 single letter email address and single
* letter domain names are permitted. */ public static boolean isValidEmailAddress(String address){ String sRegExp;

    // 050208 using the literal that was actually in place
    // 050719 tweaked 
    // 050907 tweaked, for spaces next to @ sign, two letter email left of @ ok
    // 042507 changed to allow single letter email addresses and single letter domain names
    // 080612 added trap and unit test for two adjacent @signs
    sRegExp =   "[a-z0-9#$%&]"          // don't lead with dot
        +   "[a-z0-9#$%&'\\.\\-_]*"     // more stuff dots OK
        +   "@[^\\.\\s@]"               // no dots or space or another @ sign next to @ sign
        +   "[a-z0-9_\\.\\-_]*"         // may or may  not have more character
        +   "\\.[a-z]{2,4}";            // ending with top level domain: com,. biz, .de, etc.

    boolean bTestOne =  java.util.regex.Pattern.compile( sRegExp,
            java.util.regex.Pattern.CASE_INSENSITIVE).matcher(address).matches();

    // should this work ?
    boolean bTwoDots =  java.util.regex.Pattern.compile("\\.\\.",  // no adjacent dots
                    java.util.regex.Pattern.CASE_INSENSITIVE).matcher(address).find();

    boolean bDotBefore = java.util.regex.Pattern.compile("[\\.\\s]@", //no dots or spaces before @
                         java.util.regex.Pattern.CASE_INSENSITIVE).matcher(address).find();

    return bTestOne && !bTwoDots && !bDotBefore;
}   //
answered 2009-02-03T17:41:12.357

Your Answer