在 C# 正则表达式中捕获

Captures in C# regexes

此代码应该将 img src 的值转换为本地路径。

var matches = Regex.Replace(html, "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)", 
  (match)=> {
    return string.Format("{0}{1}{2}", 
      match.Captures[0], 
      HostingEnvironment.MapPath("~/" + match.Captures[1]),
      match.Captures[2]);
});

它正确匹配了整个图片标签,但只有一张图片。我以为括号分隔了捕获,但它似乎不是那样工作的。

我应该如何写这个以获得三个捕获,中间一个是路径?

尝试使用 Groups Property 而不是 Captures,如下所示:

var matches = Regex.Replace("<img src=\"dsa\"/>", "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)", 
    (match)=> {
        return string.Format("{0}{1}{2}", 
            match.Groups[1], 
            HostingEnvironment.MapPath("~/" + match.Groups[2]),
            match.Groups[3]);
        });