简体   繁体   English

正则表达式替换和匹配

[英]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. 因此,在"////serverName/user7$/GTOUser"M.Groups[1]将返回"serverName" ,这是我需要的。 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. 我有一个也可以使用的子字符串函数,但是我想知道是否没有一种简单的方法可以使用已经存在但没有替换的正则表达式。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM