简体   繁体   English

用正则表达式替换部分字符串并提取替换值

[英]Replace part of string with Regex and extract replaced value

I have markdown content with multiple images where each image is:我有 markdown 内容,其中包含多张图片,其中每张图片是:

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

I am selecting all images in the markdown content using Regex:我正在使用 Regex 选择 markdown 内容中的所有图像:

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.对于 `content 中的每个图像路径,需要将其替换为新的 Guid。

And then add each Guid and image path to the following dictionary.然后将每个 Guid 和图像路径添加到以下字典中。

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.我试图使用Regex.Replace ,但我找不到一种方法来仅用 Guid 替换".\[?*.\]\((?*?)\)"中的图像路径,提取旧值并将两者作为键和值添加到字典中。

If I understood you correctly, this is how you can achieve that.如果我对您的理解正确,这就是您实现该目标的方法。 Do.net fiddle . Do.net 小提琴

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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