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.
CodePudding user response:
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
const regex = /^[^\s@] @(?:[^\s@.] \.)*canada\.ca$/;
[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
].forEach(s => console.log(`${s} --> ${regex.test(s)}`));
CodePudding user response:
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