Adarsh
Adarsh

Reputation: 3651

Grouping with OR in regex

The below is my regex pattern. I am using this to validate an email address.

^[\\w]+(\\.|\\_)?[\\w]+\\@{1}[\\w]+\\.{1}(([A-Za-z]+)|(\\.{1}[A-Za-z]+))$

The email ID must follow the following rules .
1. Contains any number of alphabets or numbers before 1 period or underscore.
2. Followed by any number of alphabets or numbers before 1 @.
3. Followed by any number of alphabets or numbers before 1 period.
4. (Followed by any number of alphabets) or (1 period and any number of alphabets).

I am facing an issue with the 4th rule. It works fine for a email ID ending with @xyz.abc, but fails for @xyz.abc.ab

Is it not possible to group patterns for the fourth rule as I have done ?

Solution :

"^[A-Za-z0-9]+[\\._][A-Za-z0-9]+@[A-Za-z0-9]+(?:\\.[A-Za-z]+){1,2}$"

Upvotes: 0

Views: 47

Answers (2)

Russell Zahniser
Russell Zahniser

Reputation: 16364

Based on your description, what you want is actually:

^[A-Za-z0-9]+[\\._][A-Za-z0-9]+@[A-Za-z0-9]+(?:\\.[A-Za-z]+)+$

Splitting this out, you have:

  1. Alphas or numbers ([A-Za-z0-9]+)
  2. Underscore or period ([\\._])
  3. Alphas or numbers ([A-Za-z0-9]+)
  4. At sign (@)
  5. Alphas or numbers ([A-Za-z0-9]+)
  6. One or more of period plus alphas ((?:\\.[A-Za-z]+)+)

Note that \\w contains _, so you can't use it here.

Upvotes: 2

Chandranshu
Chandranshu

Reputation: 3669

Use this:

^[\\w]+(\\.|\\_)?[\\w]+\\@{1}[\\w]+(\\.{1}[\\w]+)+$

I should also point out that the actual regex for email is pretty complex. I hope you are not using it for any real checks on a website.

Upvotes: 1

Related Questions