need a c# regex to get servername out of UNC
Question
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.
OTHER TIPS
Why use regex when Uri
will do it too?
Uri uri = new Uri(@"\\servername\d$\directory");
Console.WriteLine(uri.Host); // servername
Console.WriteLine(uri.IsUnc); // true
This task is simple enough that it does not really require a regex (it would very much be overkill).
Try this approach, which uses a simple call to string.Split
. It should allow you to get each part of the path trivially (though you say you don't need that).
var uncPath = @"\servername\d$\directory";
var serverName = uncPath.Split('\')[1];
If you wanted to do the parsing fully manually, it's still quite straightforward:
var serverName = uncPath.Substring(1, uncPath.IndexOf('\', 1) - 1);
Since you are trying to do it with regex, here is how i would do it. this produces the results you wanted.
string s = @"**\\\servername\d$\directory**";
Console.WriteLine(Regex.Match(s, @"[A-Za-z][A-Za-z0-9]*").Captures[0].Value);
Console.ReadLine();
produces servername
you might have to allow for some other potential servername characters like - and _ but this is the basic idea.
But using the Uri class is probably the best way to solve this specific problem.