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.

3
  • Why are you matching an @? The current pattern does not match any of the above Commented Mar 7, 2022 at 20:57
  • They are email addresses we are checking against. Left that off. sorry Commented Mar 7, 2022 at 20:59
  • 1
    Like this? ^[^\s@]+@(?:[^\s.]+\.)*canada\.ca$ regex101.com/r/etLosM/1 Commented Mar 7, 2022 at 21:01

2 Answers 2

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)}`));

Sign up to request clarification or add additional context in comments.

3 Comments

That works. Now I need to use it to learn from. Thank you
@VisualSP-DEV This is a pretty good site for visualizing regexes
Thanks, @Gary - I will look at that
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

4 Comments

That would allow things like "[email protected]"
@Blindy - thanks, I will look at you solution as well.
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 :)
I think this falls outside the spirit of the question by matching other valid/simple domains. But I agree with your overall point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.