Stanley Mungai
Stanley Mungai

Reputation: 4150

Email address validation fails when domain name has a hyphen

I have an email address validation regex Which I use in the code like this:

public class Test {

  public static void main(String[] args) {
    try {
      String lineIwant = "[email protected]";
      String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
      Boolean b = lineIwant.matches(emailreg);

      if (b == false) {
        System.out.println("Address is Invalid");
      }else if(b == true){
        System.out.println("Address is Valid");
      }
    } catch (Exception e) {

      e.printStackTrace();
      System.out.println(e.getMessage());
    }
  }
}

On this specific email address in the example, the Boolean returns false while this is a valid customer email address.

I am suspecting it is because of the hyphen between ramco and group because when I remove it the Boolean returns true.

How can I change my regex to accommodate such an email address?

Upvotes: 0

Views: 38508

Answers (4)

Duncan Jones
Duncan Jones

Reputation: 69339

I would recommend you don't try to solve this problem yourself. Instead, rely on a well-tested solution such as EmailValidator from commons-validator.

For example:

EmailValidator.getInstance().isValid(emailAddressString);

Upvotes: 16

gmustudent
gmustudent

Reputation: 2209

Add \\- to that section of the regex string after the @.

The \\ is an escape telling Java that you do not want to use the dash as it's normally used to show the difference between two values. So like this...

^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9\\-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$

Update

Tim acknowledged in the comments that the escape is not necessary!

And a quick tip of my own is you might want to use \w in replace of [A-Za-z0-9_] so you don't have to keep writing that over and over. And finally get familiar with this site. Once you start using regex it's a great help.

Upvotes: 2

MarekM
MarekM

Reputation: 1466

there are many regexp validation strings, that you can use. Like here

but it is realy nescesary to have Optimal solution? Don't need you only sub optimal solution that covers 99.9999% used adresses?

read this article

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336198

Your regex is not allowing a - after the @ sign, so

String emailreg = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";

would "fix" this specific problem. But Email addresses are much more complicated than that. Validating them using a regex is not a good idea. Check out @DuncanJones' comment.

Upvotes: 16

Related Questions