繁体   English   中英

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

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

我有 markdown 内容,其中包含多张图片,其中每张图片是:

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

我正在使用 Regex 选择 markdown 内容中的所有图像:

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

有了这个,我为每场比赛得到两组:

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

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

对于 `content 中的每个图像路径,需要将其替换为新的 Guid。

然后将每个 Guid 和图像路径添加到以下字典中。

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

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

如果我对您的理解正确,这就是您实现该目标的方法。 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