0

I am looking for a REGEX (JS) that I can use to match all subdomains for a domain as well as the TLD domain in email addresses.

Here is an example:

I would like to be able to match any the following:

  • joe@canada.ca
  • joe@it.canada.ca
  • joe.smith@business.canada.ca

But not match

  • joe@visitcanada.ca

By default we use something like:

/(.*)@(.*)canada\.ca/gm

But this matches all of the above. Would ideally like a single REGEX that will accomplish all of this.

2 Answers2

1

You could use

^[^\s@]+@(?:[^\s@.]+\.)*canada\.ca$
  • ^ Start of string
  • [^\s@]+ Match 1+ chars other than a whitespace char or @
  • @ Match literally
  • (?:[^\s@.]+\.)* Match optional repetitions of 1+ chars other than a whitespace char, @ or dot, and then match the .
  • canada\.ca Match canada.ca (Note to escape the dot to match it literally
  • $ End of string

Regex 101 demo.

const regex = /^[^\s@]+@(?:[^\s@.]+\.)*canada\.ca$/;
[
  "joe@canada.ca",
  "joe@it.canada.ca",
  "joe.smith@business.canada.ca",
  "joe@visitcanada.ca",
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

An easier way is to simply anchor canada to a word boundary using \b, that way you can use your regex pretty much word for word:

.*@.*\bcanada\.ca
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • That would allow things like "joe@visit-canada.ca" – Gary Mar 07 '22 at 21:14
  • @Blindy - thanks, I will look at you solution as well. –  VisualSP - DEV Mar 07 '22 at 21:16
  • Well we're talking about regex here and parsing email addresses. No matter how good you are and how many pages of regex you write, it still won't be RFC-conforming. This is simple and it matches every one of the OP's test cases :) – Blindy Mar 07 '22 at 21:17
  • I think this falls outside the spirit of the question by matching other valid/simple domains. But I agree with your overall point. – Gary Mar 07 '22 at 21:25