sasuke
sasuke

Reputation: 201

How to match all email addresses at a specific domain using regex?

I need help on finding a regex expression that will match email addresses of only a specific domain

As in any .*@testdomain.com

And also the opposite any thing other than .*@testdomain.com

Upvotes: 20

Views: 90530

Answers (5)

Ajit Vaniya
Ajit Vaniya

Reputation: 1

You can also set as below regex.

/^[a-zA-Z0-9._%+-]+@testdomain\.com$/gm

Upvotes: -2

Marcello Faga
Marcello Faga

Reputation: 1204

I propose an expression very simple:

^[A-Za-z0-9._%+-]+@testdomain\.com$

The . in the domain must be escaped as well.

and for the negative check:

^[A-Za-z0-9._%+-]+@(?!testdomain.com)[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$

Upvotes: 52

SoftDev30_15
SoftDev30_15

Reputation: 503

@Kushal I found an easy way to do this, but it was somewhat tricky, because I had to retrieve via ajax the domain from a global variable stored somewhere else.

Here is the following line of code inside a javascript validation method:

return new RegExp("^\\w+([-+.']\w+)*@"+getDomain.responseJSON.d+"$").test(value.trim());

I create a new RegExp on the spot and test the value (email input) to see if it matches the domain.

  • The string inside quotes is the regex that may contain any kind of name the user has.
  • The getDomain.responseJSON.d, is the dynamic global domain variable (in case I want it changed and did not want to interfere with the source code.) that was retrieved with a $.getJSON(); call to a WCF service.

If you want something more elaborate but have standard domains, then it can go like this:

return /^\w+([-+.']\w+)*@?(example1.com|example2.com)$/.test(value.trim());

Upvotes: 1

Kushal
Kushal

Reputation: 1189

For my particular scenario, I needed this variation:

'^[A-Za-z0-9._%+-]+@' + email_domain + '$'

this would match an email_domain from a list of email_domains: ['example1.com', 'example2.co.uk'] and I was running through the list, matching each one against a list of email addresses.

Upvotes: 2

siddardha
siddardha

Reputation: 200

grep -oE '( |^)[^ ]*@testdomain\.com( |$)' file.txt

-o Returns only the matched string

The above will give all email id's of testdomain in file.txt.

Upvotes: 0

Related Questions