15

谁能告诉我如何从 UNC 中提取服务器名称?

前任。

//服务器名/目录/目录

编辑:我很抱歉,但看起来我需要澄清一个错误:路径实际上更像:

//服务器名/d$/目录

我知道这可能会改变一些事情

4

5 回答 5

24

怎么样Uri

Uri uri = new Uri(@"\\servername\d$\directory");
string[] segs = uri.Segments;
string s = "http://" + uri.Host + "/" + 
    string.Join("/", segs, 2, segs.Length - 2) + "/";
于 2009-06-27T19:21:53.827 回答
7

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.
于 2009-06-27T17:47:59.470 回答
3

这应该可以解决问题。

^//([^/]+).*

服务器名称在第一个捕获组中

于 2009-06-27T17:14:10.480 回答
1

要匹配的正则表达式servername

^//(\w+)
于 2009-06-27T17:17:24.173 回答
0

丑陋但它只是工作:

var host = uncPath.Split(new [] {'\\'}, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();
于 2016-10-06T15:24:22.517 回答