1

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?

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
  • What is your input string? – Andrey Jun 05 '17 at 01:11
  • Also don't use Regex for parsing HTML – Andrey Jun 05 '17 at 01:13
  • @Andrey as a general rule I heartily agree. In this case I'm using HTML as template mark up that I stuff through an html to pdf converter. A shortcoming of the converter is it doesn't resolve resources unless you specify an absolute local filesystem path. Automatically resolving web relative paths in the code that stuffs HTML through the converter means I can have a template that renders as a web page consumable by a browser for preview and testing. – Peter Wone Jun 05 '17 at 04:57

1 Answers1

1

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]);
        });
Frederik Hansen
  • 506
  • 4
  • 21
  • Yes I just discovered this myself. What are captures then, since this is groups? If there were four image tags would there be four captures, is that what a capture is? – Peter Wone Jun 05 '17 at 01:20
  • 1
    [This post](https://stackoverflow.com/questions/3320823/whats-the-difference-between-groups-and-captures-in-net-regular-expression) has some good answers for that. – Frederik Hansen Jun 05 '17 at 01:25