TrevorGoodchild
TrevorGoodchild

Reputation: 1058

Regex.Replace and Match

I have a function where I need to strip out leading and trailing slashes within a file path to just get the server name. The path won't necessarily always have the leading slashes.

Here's what I found in another section of our app:

public static string ResolveToIP(string path) {
    return Regex.Replace(path, @"^\\\\(.*?)\\(.*)$",
        delegate(Match M) {
        try {
            IPAddress[] addresses = System.Net.Dns.GetHostAddresses(M.Groups[1].Value);
return "\\\\" + addresses[0].ToString() + "\\" + M.Groups[2].Value;
            } 
        catch {
              return path;
              }
            });
        }

So in the case of "////serverName/user7$/GTOUser", M.Groups[1] will return "serverName", which is what I need. I've got a substring function that will also work but I'm wondering if there isn't an easy way to use that same Regex that's already there but without the replace.

Upvotes: 0

Views: 74

Answers (1)

TrevorGoodchild
TrevorGoodchild

Reputation: 1058

I figured it out, much simpler than I thought:

string pattern = @"^\\\\(.*?)\\(.*)$";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = r.Match(AS.SourcePath);
string server = m.Groups[1].Value;

Upvotes: 2

Related Questions