I can’t figure this out. I need to extract the second level domain from a FQDN. For example, all of these need to return “example.com”:
- example.com
- foo.example.com
- bar.foo.example.com
- example.com:8080
- foo.example.com:8080
- bar.foo.example.com:8080
Here’s what I have so far:
Dim host = Request.Headers("Host")
Dim pattern As String = "(?<hostname>(\w+)).(?<domainname>(\w+.\w+))"
Dim theMatch = Regex.Match(host, pattern)
ViewData("Message") = "Domain is: " + theMatch.Groups("domainname").ToString
It fails for example.com:8080 and bar.foo.example.com:8080. Any ideas?
I used this Regex successfully to match “example.com” from your list of test cases.
The dot character (“.”) needs to escaped as “\.”. The “.” character in a regex pattern matches any character.
Also the regex pattern you provided requires that there be 1 or more word characters followed by a dot before the domainname match (this part “(?(\w+)).” of the pattern. Also, I’m assuming that the . character was supposed to be escaped). This fails to make a match for the input “example.com” because there’s no word character and dot before the domainname match.
I changed the pattern so that the hostname match would have zero or more matches of “1 or more word characters followed by a dot”. This will match “foo” in “foo.example.com” and “foo.bar” in “foo.bar.example.com”.