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:

But not match

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$/;
[
  "[email protected]",
  "[email protected]",
  "[email protected]",
  "[email protected]",
].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