Peter Wone
Peter Wone

Reputation: 18755

Captures in C# regexes

This code is supposed to convert the value of img src to a local path.

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]);
});

It matches the whole image tag correctly but there's only one capture. I thought the parentheses delimited captures but it doesn't seem to be working like that.

How should I have written this to get three captures, the middle one being the path?

Upvotes: 1

Views: 62

Answers (1)

Frederik Hansen
Frederik Hansen

Reputation: 506

Try using the Groups Property instead of Captures, like so:

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]);
        });

Upvotes: 1

Related Questions