正则表达式用于从FQDN中提取二级域名? [英] Regex for extracting second level domain from FQDN?
问题描述
我不知道这一点.我需要从FQDN中提取第二级域.例如,所有这些都需要返回"example.com":
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
对于example.com:8080
和bar.foo.example.com:8080
,它将失败.有什么想法吗?
It fails for example.com:8080
and bar.foo.example.com:8080
. Any ideas?
推荐答案
我成功使用了此Regex来匹配您的测试用例列表中的"example.com".
I used this Regex successfully to match "example.com" from your list of test cases.
"(?<hostname>(\w+\.)*)(?<domainname>(\w+\.\w+))"
点字符(.")需要转义为"\.".这 "."正则表达式模式中的字符与任何字符匹配.
The dot character (".") needs to escaped as "\.". The "." character in a regex pattern matches any character.
此外,您提供的regex模式要求在域名匹配(模式的这一部分(?(\ w +))")之前必须有1个或多个单词字符,后跟一个点.此外,我假设字符应该被转义).域名匹配之前没有单词和点,因此无法匹配输入的"example.com".
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.
我更改了模式,以便主机名匹配具有零个或多个"1个或多个单词字符后跟一个点"的匹配项.这将匹配"foo.example.com"中的"foo"和"foo.bar.example.com"中的"foo.bar".
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".
这篇关于正则表达式用于从FQDN中提取二级域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!