简体   繁体   中英

Replace part of string with Regex and extract replaced value

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.

If I understood you correctly, this is how you can achieve that. Do.net 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM