Search code examples
c#regexurluriunc

need a c# regex to get servername out of UNC


I screwed up my last post. Lets see if I can get this one right..

Would anyone be able to tell me how to pull the server name out of a UNC? (I'm looking for a regex)

this is the string I want to pull the servername from:

**\\\servername\d$\directory**

My Code is in C#

Regex r = new Regex(?????, RegexOptions.IgnoreCase);

Match m = r.Match(@"\\servername\d$\directory"); 

CaptureCollection cc = m.Captures;

foreach (Capture c in cc)
{

    System.Console.WriteLine(c);

}

I am looking to capture just: servername

no slashes or anything.


Solution

  • Note: This answer is for education purposes - better to use the Uri object and not re-invent existing functions.

    Same solution as on the other question, but with backslashes reversed, and therefore escaped, (and possessive quantifier removed, since C# regex doesn't support that):

    (?<=^\\\\)[^\\]+
    


    The server name will be in \0 or $0 or simply the result of the function, depending on how you call it and what C# offers.


    Explanation in regex comment mode:

    (?x)      # flag to enable regex comments
    (?<=      # begin positive lookbehind
    ^         # start of line
    \\\\      # escaped backslashes to give literal \\ chars.
    )         # end positive lookbehind
    [^\\]+    # greedily match any non-\ until a \ or end of string found.