1
votes

I'm trying to create a regex that will optionally match any subdomains, and match the TLD. For example, it should match…

It should not match…

I have this so far, which matches subdomains, but does not match when at the top level domain. (\A|(https?:\/\/))?(\w*|\S*)\.{1}example\.com

1
Thanks, that worked!Daniel Jacob Archer
This problem cannot be solved with a regex, because the exact same domain path may refer to a top-level domain or not, depending on the client's network. In particular, the domain paths you posted are all relative, not absolute paths, so they are looked up relative to the client's default suffix. For example, if I work for a company named "Foo" in Germany, which owns the domain foo.de, and it's communications department is using the domain com and has a server called example, then the DNS query for example.com will actually return the address of example.com.foo.de..Jörg W Mittag
What is wrong with the answer below?Wiktor Stribiżew

1 Answers

2
votes

You may use

/\A(?:https?:\/\/)?(?:\S*\.)?example\.com\z/

See the regex demo

Details

  • \A - start of string
  • (?:https?:\/\/)? - an optional (as the ? quantifier at the end repeats 1 or 0 times) non-capturing group matching http, an optional s and then // substring
  • (?:\S*\.)? - an optional non-capturing group matching 1 or 0 occurrences of 0 or more non-whitespace chars (with \S*) and then a dot (\.)
  • example\.com - an example.com substring
  • \z - end of string.