谁能告诉我如何从 UNC 中提取服务器名称?
前任。
//服务器名/目录/目录
编辑:我很抱歉,但看起来我需要澄清一个错误:路径实际上更像:
//服务器名/d$/目录
我知道这可能会改变一些事情
怎么样Uri
:
Uri uri = new Uri(@"\\servername\d$\directory");
string[] segs = uri.Segments;
string s = "http://" + uri.Host + "/" +
string.Join("/", segs, 2, segs.Length - 2) + "/";
Just another option, for the sake of showing different options:
(?<=^//)[^/]++
The server name will be in \0
or $0
or simply the result of the function, depending on how you call it and what your language offers.
Explanation in regex comment mode:
(?x) # flag to enable regex comments
(?<= # begin positive lookbehind
^ # start of line
// # literal forwardslashes (may need escaping as \/\/ in some languages)
) # end positive lookbehind
[^/]++ # match any non-/ and keep matching possessively until a / or end of string found.
# not sure .NET supports the possessive quantifier (++) - a greedy (+) is good enough here.
这应该可以解决问题。
^//([^/]+).*
服务器名称在第一个捕获组中
要匹配的正则表达式servername
:
^//(\w+)
丑陋但它只是工作:
var host = uncPath.Split(new [] {'\\'}, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();