0

I'm trying to create a regular expression which will work on an email. I need to match that an email is either from a certain domain or from a certain domain and subdomain. A domain must be matched precisely.

I have this:

@.*\.?somedomain\.com$

Yes, this will match:

  fdsafd@a1.somedomain.com
  fdsafd@somedomain.com
  fdsafd@aabbddjjj.somedomain.com

which is what I need. However, it'll also a domain which contains somedomain.com as a part in it, and this isn't what I want:

fdsafd@partsomedomain.com

I want the domain somedomain.com to be matched precisely.

How to fix it?

kosmosu
  • 53
  • 1
  • 6
  • 1
    You need to make the whole subdomain optional, not just the dot. Instead of `.*\.?`, use something like `(?:.*\.)?` ([demo](https://regex101.com/r/JakOtR/1)). Moreover, you probably should replace the `.*` part with something [more strict](https://stackoverflow.com/q/7111881/8967612). – 41686d6564 Sep 21 '20 at 13:12
  • @41686d6564 I was going with another solution, realised I was wrong and now I've posted an answer which is basically your comment. Tell me if you post it as an answer, I'll delete mine. – Aaron Sep 21 '20 at 14:43
  • @41686d6564 why is `?:` needed? – kosmosu Sep 21 '20 at 16:10
  • @Aaron That's fine. It doesn't matter who posted the answer as long as the OP got their problem solved :) – 41686d6564 Sep 21 '20 at 22:03
  • @kosmosu It's called a [non-capturing group](https://stackoverflow.com/q/3512471/8967612). – 41686d6564 Sep 21 '20 at 22:03

2 Answers2

1

I would match the following :

@(.*\.)?somedomain\.com$

somedomain is guaranteed to be a whole DN path rather than part of one as it either follows the ending . of the optional group or the @ that precedes it.

Aaron
  • 21,986
  • 2
  • 27
  • 48
0

Try below:

\w+\.com

It will select .com and the word preceding it.

Homer
  • 364
  • 1
  • 7