Meek
Meek

Reputation: 3348

Regex: how to match list of specific domains

I need a regex which will match a specific list of domains in e-mail addresses. I know this is probably not a popular issue, but it's for internal use, and for a limited list of e-mail addresses. I have like 10-12 domains that I need to be able to match.

The domain names do not contain sub domains or dots and the suffix is always the same, like:

*@onedomain.com
*@anotherdomain.com
*@thirddomain.com

I have tried with this:

/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@(?i)(onedomain|anotherdomain|thirddomain|domain4)\.com$/

But I get this error: Invalid syntax. Can anybody help with this, please? Thanks.

Upvotes: 0

Views: 2835

Answers (4)

rvalvik
rvalvik

Reputation: 1559

I know you asked for a regex solution, but if the list of domains is long, you might want to consider not doing it purely in regex. 10-12 domains could make for one long nasty expression.

Instead you can use regex to match a basic email format, and then keep an array of whitelisted domains that are allowed. That way you don't need to put all the domains into the expression itself.

function isValidEmail(address) {
    var domains = ["onedomain","anotherdomain","thirddomain","domain4"];

    // Basic .com email matching
    var regex = /^[\w-]+(?:\.[\w-]+)*@(.*)\.com$/i;
    var matches = regex.exec(email);

    // Assert that address is an .com email address 
    if (matches === null)
        return false;

    // return true if domain is in whitelist, false otherwise
    return (domains.indexOf(matches[1]) != -1);
}

Changing @(.*)\.com to @(.*\..{2,}) will enable you to put the full domain in the whitelist array should you need to match other domains than .com you'd then have to put domain4.com etc. in the array instead.

Upvotes: 1

Toto
Toto

Reputation: 91385

It seems you can't use (?i) with javascript regex.

You have to use the /i modifier instead.

pattern = new RegExp('^[\w-]+(\.[\w-]+)*@(onedomain|anotherdomain|thirddomain|domain4)\.com$','i')

Upvotes: 2

Markus
Markus

Reputation: 1767

Try this regex to match @domainX.com:

[A-Za-z0-9!#$%&’*+-/=?^_`\.{|}~]+@domain[1-4]\.com

it matches

[email protected]
[email protected]

and much more

EDIT

to match every domain use this regex:

[A-Za-z0-9!#$%&’*+-/=?^_`\.{|}~]+@([a-z0-9_-]+[\.]?)*

Upvotes: 0

Theox
Theox

Reputation: 1363

If the issue is about the regex, you could try this :

/^[\w-\.]+@domain(1|2|3|4)\.com$/

About your regex : I think the syntax error is in the (?i) part. I don't really see what is this group for, and it is invalid.

Upvotes: 0

Related Questions