Quantcast
Channel: Solved » regex
Viewing all articles
Browse latest Browse all 14

Java Regular Expression to Validate an Email Address

$
0
0

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 = "myname@asl.ramco-group.com";
      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?

Solution

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.

The post Java Regular Expression to Validate an Email Address appeared first on Solved.


Viewing all articles
Browse latest Browse all 14

Trending Articles