A.Jha
A.Jha

Reputation: 15

Restrict particular domain in email regular expression

I have an existing regex which validates the email input field.

[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!$%&'*+/=?^_`{|}~-]+)*(\\.)?@(?:[a-zA-Z0-9ÄÖÜäöü](?:[a-zA-Z0-9-_ÄÖÜäöü]*[a-zA-Z0-9_ÄÖÜäöü])?\\.)+[a-zA-Z]{2,}

Now, I want this regex to not match for two particular type of email IDs. Which are wt.com and des.net

To do that I made the following changes in the above expression like this.

[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!$%&'*+/=?^_`{|}~-]+)*(\\.)?@(?!wt\\.com)(?!des\\.net)(?:[a-zA-Z0-9ÄÖÜäöü](?:[a-zA-Z0-9-_ÄÖÜäöü]*[a-zA-Z0-9_ÄÖÜäöü])?\\.)+[a-zA-Z]{2,}

After this it does not matches with any email id which ends with the wt.com and des.net which is right. But the problem is it does not match with wt.comm or any other letter after the restricted string too.. I just want to restrict email which ends with wt.com and des.net How do I do that? Below is the sample emails which should match or not.

  1. [email protected] : no match
  2. [email protected] : match
  3. [email protected] :match
  4. [email protected] : no match
  5. [email protected]: match

Upvotes: 1

Views: 1149

Answers (1)

Pshemo
Pshemo

Reputation: 124215

If you want to prevent only wt.com and des.net which have no characters after it you can add $ anchor (which represents end of string) at the end of each negative-look-ahead.

So instead of (?!wt\\.com)(?!des\\.net) use (?!wt\\.com$)(?!des\\.net$)

Upvotes: 1

Related Questions