RegEx: Find domains and subdomains based on a whitelist

Viewed 227

I have this list:

something.microsoft.com
something.bing.de
somethingmicrosoft.com
something-bing.com
microsoft.com
bing.de

My goal is to filter the domains that have subdomains or nothing at all. So in the end it should look like this:

something.microsoft.com
something.bing.de
microsoft.com
bing.de

There should be a whitelist in the regular expression, so only selected substrings are allowed for the SLD and TLD (separated).

This is what I tried so far:

(?:.*)\.{0,1}(?:microsoft|bing)(?:\.de|\.com)
(?:.*\.){0,1}(?:microsoft|bing)(?:\.de|\.com)

As you can see it also finds somethingmicrosoft.com. How can I achieve my goal?

1 Answers

You can use

^(?:.*\.)?(?:microsoft|bing)\.(?:de|com)$

See the regex demo. Details:

  • ^ - start of string
  • (?:.*\.)? - an optional sequence of any chars other than line break chars, as many as possible, followed with a literal . char
  • (?:microsoft|bing) - microsoft or bing
  • \. - a dot
  • (?:de|com) - de or com
  • $ - end of string.
Related