1

I have markdown content with multiple images where each image is:

![Image Description](/image-path.png)

I am selecting all images in the markdown content using Regex:

var matches = new Regex(@"!\[.*?\]\((.*?)\)").Matches(content);

With this I get two groups for each match:

Groups[0] = ![Image Description](/image-path.png);  > (Everything)

Groups[1] = /image-path.png                         > (Image Path)  

For each image path in `content need to replace it by a new Guid.

And then add each Guid and image path to the following dictionary.

Dictionary<String, String> imagePathsKeys = new Dictionary<String, String>();

I was trying to use Regex.Replace but I can't find a way to replace only the image path in "!\[.*?\]\((.*?)\)" with a Guid, extract the old value and add both to the dictionary as Key and Value.

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Did you try escaping the exclamation mark? Also try double escaping any special characters. I am not familiar with C# regex but it seems to me that the regex is passed as a string. – Wais Kamal Feb 11 '22 at 16:43
  • 1
    see if this helps https://stackoverflow.com/questions/6005609/replace-only-some-groups-with-regex – Rajesh G Feb 11 '22 at 16:45

1 Answers1

0

If I understood you correctly, this is how you can achieve that. Dotnet fiddle.

Dictionary<String, String> imagePathsKeys = new Dictionary<String, String>();

var content = "![First Image Description](/image-path.png) ![Second Image Description](/image-path.png)";

// This regex will only match whatever is between / and .
// You may have to play around with it so it finds image names more accurately in your actual project
var matches = new Regex(@"(?<=\/)(.*?)(?=\.)").Matches(content); 

foreach (Match match in matches)
{
    GroupCollection groups = match.Groups;

    var guid = Guid.NewGuid().ToString(); // generating new guid

    imagePathsKeys.Add(guid, groups[0].Value); // adding new guid as key and image path as value

    content = content.Replace(groups[0].Value, guid); // replacing image path with new guid
}
Oleg Naumov
  • 545
  • 1
  • 3
  • 10