Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull the server name from a UNC

Tags:

c#

regex

uri

Would anyone be able to tell me how to pull the server name out of a UNC?

ex.

//servername/directory/directory

Edit : I apologize but it looks like I need to clarify a mistake: the path actually is more like:

//servername/d$/directory

I know this might change things a little

like image 758
KevinDeus Avatar asked Jun 27 '09 17:06

KevinDeus


2 Answers

How about Uri:

Uri uri = new Uri(@"\\servername\d$\directory");
string[] segs = uri.Segments;
string s = "http://" + uri.Host + "/" + 
    string.Join("/", segs, 2, segs.Length - 2) + "/";
like image 184
Marc Gravell Avatar answered Oct 04 '22 00:10

Marc Gravell


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.
like image 37
Peter Boughton Avatar answered Oct 03 '22 23:10

Peter Boughton