Bobby Bruce
Bobby Bruce

Reputation: 361

How to write a conditional in regex

I have the follow line of regex (javascript)

/^[a-z0-9_.\-]+@(yahoo|gmail|excite})\.com$/

However, I am unsure of how to make this include subdomains (IF one is present).

So this expression should match uk.yahoo.com and yahoo.com email address as well... How can this be done?

Upvotes: 1

Views: 58

Answers (1)

yossarian
yossarian

Reputation: 1667

Well, if you want just the subdomain uk.yahoo.com:

/^[a-z0-9_.\-]+@((?:uk\.)?yahoo|gmail|excite)\.com$/

The addition of (?:uk\.)? specifies a optional noncapturing group that matches either 0 or 1 occurrence of the pattern "uk.".

However, using regexes to validate email addresses is an awful idea. RFC2822 is a very complex standard. It's much better to blindly send an email to whatever minimally-validated address the user enters, fail early, and give the user a chance to correct the mistake.

Upvotes: 1

Related Questions