tags:

views:

256

answers:

4

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

+3  A: 

This should do the trick.

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

The server name is in the first capturing group

jitter
At the start of a line (^), match two forward slashes (//), then one or more (+) characters that's not another forward slash ([^/]) followed by one or more occurrences of anything (.*) The parens "(" and ")" indicate a 'capturing group'.
Adam Bernier
@Adam: Thanks for explaining how the regular expression actually works.
Jason Down
@Jason: happy to do so. A mistake in my explanation: the * symbol is not 'one or more', it is 'zero or more'. The + symbol is 'one or more'
Adam Bernier
using comment 1 here I get the following in c#://servername/is there a way to strip off the slashes?(my program)Regex r = new Regex(@"^//(?<serverName>\w+)/", RegexOptions.IgnoreCase);Match m = r.Match(@"//servername/directory/directory");CaptureCollection cc = m.Captures;foreach (Capture c in cc){ System.Console.WriteLine(c);}
KevinDeus
+1  A: 

Regular expression to match servername:

^//(\w+)
Alan Haggai Alavi
I'm a fan of named capture groups, so I'd probably modify this to: ^//(?<serverName>\w+)/
Lee
\w will match [A-Za-z0-9_] - but server names can contain many more characters than those?
Peter Boughton
+3  A: 

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.
Peter Boughton
+1 for a very thorough and well-explained answer.
Adam Bernier
I tried this one in C# and got the following error message: parsing "(?<=^//)[^/]++" - Nested quantifier +.
KevinDeus
@Kevin: just drop the second + symbol.
Adam Bernier
+1  A: 

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) + "/";
Marc Gravell