获取 URI 的一部分
Getting parts of a URI
假设我有这个代码:
Uri uri = new Uri("www.xx.yy.co.uk/folder/whatever.html");
如何从 C# 中的 Uri
获取 xx
、 yy
、 co.uk
?我几乎尝试了 Uri
class 中的每一个 属性,但我没有找到任何相关的东西。
请注意,例如,com
和 co.uk
都是一个字符串。
如您所见,内置 System.Uri 不会分解 URL 的各个顶级 (host/domain) 部分。您要求的解析类型非常具体,因为 .com
和 .co.uk
不是 URL 中的等效组件(.com 和 .uk 是)。
您自己执行此操作的两种简单方法是:
在正则表达式中修改一个established regex for parsing the URL held in the Host
property of the Uri, and use named captures (groups)以方便提取部分。
通过创建您自己的继承自 System.Uri class 来扩展 System.Uri,并引入一种以您想要的特定方式分解 URL 的方法.
这将适用于此问题。检查数组元素:
Uri uri = new Uri("http://www.xx.yy.co.uk/folder/whatever.html");
string abs = uri.AbsoluteUri;
char[] splitChar = { '.' };
var nodesArray = abs.Split(splitChar).ToArray();
问题是 "pseudo top-level domains" 的列表非常大,例如 co.uk、wakayama.jp 或 edu.cn,甚至 "top-level domains"三个部分。在 C# 中没有所有这些的内置列表,所以我能看到的最好的解决方案是指定你期望的那些并在它们上分开,如下所示:
List<string> parts = null;
Uri uri = new Uri("http://www.xx.yy.co.uk/folder/whatever.html");
string s = uri.Host;
string[] twoLevelDomains = { "co.uk", "edu.cn" };
foreach(var twoLevelDomain in twoLevelDomains)
{
if (s.EndsWith(twoLevelDomain))
{
parts = s.Replace("." + twoLevelDomain, "").Split('.').ToList();
parts.Add(twoLevelDomain);
}
}
if(parts == null) {
parts = s.Split('.').ToList();
}
背景:
唯一的官方顶级域名只是其中的一部分,比如.uk。此处提供了所有 "pseudo top-level domains" 的比较全面的列表:https://wiki.mozilla.org/TLD_List。虽然这是一个很大的列表,但似乎并不全面,因为列出的许多国家/地区只有 1 个顶级域,并且还有诸如“(其他?)”之类的字段。
假设我有这个代码:
Uri uri = new Uri("www.xx.yy.co.uk/folder/whatever.html");
如何从 C# 中的 Uri
获取 xx
、 yy
、 co.uk
?我几乎尝试了 Uri
class 中的每一个 属性,但我没有找到任何相关的东西。
请注意,例如,com
和 co.uk
都是一个字符串。
如您所见,内置 System.Uri 不会分解 URL 的各个顶级 (host/domain) 部分。您要求的解析类型非常具体,因为 .com
和 .co.uk
不是 URL 中的等效组件(.com 和 .uk 是)。
您自己执行此操作的两种简单方法是:
在正则表达式中修改一个established regex for parsing the URL held in the
Host
property of the Uri, and use named captures (groups)以方便提取部分。通过创建您自己的继承自 System.Uri class 来扩展 System.Uri,并引入一种以您想要的特定方式分解 URL 的方法.
这将适用于此问题。检查数组元素:
Uri uri = new Uri("http://www.xx.yy.co.uk/folder/whatever.html");
string abs = uri.AbsoluteUri;
char[] splitChar = { '.' };
var nodesArray = abs.Split(splitChar).ToArray();
问题是 "pseudo top-level domains" 的列表非常大,例如 co.uk、wakayama.jp 或 edu.cn,甚至 "top-level domains"三个部分。在 C# 中没有所有这些的内置列表,所以我能看到的最好的解决方案是指定你期望的那些并在它们上分开,如下所示:
List<string> parts = null;
Uri uri = new Uri("http://www.xx.yy.co.uk/folder/whatever.html");
string s = uri.Host;
string[] twoLevelDomains = { "co.uk", "edu.cn" };
foreach(var twoLevelDomain in twoLevelDomains)
{
if (s.EndsWith(twoLevelDomain))
{
parts = s.Replace("." + twoLevelDomain, "").Split('.').ToList();
parts.Add(twoLevelDomain);
}
}
if(parts == null) {
parts = s.Split('.').ToList();
}
背景: 唯一的官方顶级域名只是其中的一部分,比如.uk。此处提供了所有 "pseudo top-level domains" 的比较全面的列表:https://wiki.mozilla.org/TLD_List。虽然这是一个很大的列表,但似乎并不全面,因为列出的许多国家/地区只有 1 个顶级域,并且还有诸如“(其他?)”之类的字段。