-1

I want to do basic email validation in java using regex and I came up with following regex

private static final String EMAIL_REGEX = "^\\s*(.+)@(.+)\\.(.+)\\s*$";

If we take test@gmail.com under this regex.

1. Ignore starting and trailing white spaces.
2. 1 or more char for username  (test)
3. @
4. one or more char for domain (gmail)
5. .
6. one or more char for domain extension(com).

Is it correct as per my requirement?

I have checked Apache EmailValidator but it does some validation of domain also, eg. when i tried it with test@gmail.adpcc, then it did not work. And I want it to work as per my use case.

InSync
  • 4,851
  • 4
  • 8
  • 30
user124
  • 423
  • 2
  • 7
  • 26

1 Answers1

-1

The regex you provided is a basic email validation pattern, and it seems to meet your requirements as described. However, it is not very strict and may allow some invalid email addresses to pass through. Here's the regex you provided:

private static final String EMAIL_REGEX = "^\\s*(.+)@(.+)\\.(.+)\\s*$";

This regex will match email addresses with the format you described, ignoring leading and trailing whitespace, and requiring at least one character for the username, domain, and domain extension. However, it does not impose any restrictions on the types of characters that can appear in the username, domain, or domain extension.

If you want to improve the regex to be slightly more strict, you can use the following pattern:

private static final String EMAIL_REGEX = "^\\s*([\\w!#$%&'*+\\-/=?^_`{|}~]+(?:\\.[\\w!#$%&'*+\\-/=?^_`{|}~]+)*)@([\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z]{2,}\\s*$";

This pattern allows for a wider range of valid characters in the username and domain, while also checking for valid domain extensions consisting of at least two alphabetic characters. However, it still may not cover all valid email addresses or reject all invalid ones.

The Apache Commons EmailValidator is more comprehensive in its validation, but as you mentioned, it may not suit your use case. If the regex pattern above works for your specific requirements, then you can use it for your basic email validation.