'Replace part of string with Regex and extract replaced value
I have markdown content with multiple images where each image is:

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] = ; > (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.
Solution 1:[1]
If I understood you correctly, this is how you can achieve that. Dotnet fiddle.
Dictionary<String, String> imagePathsKeys = new Dictionary<String, String>();
var content = " ";
// 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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oleg Naumov |
