[英]Regex replace all occurences with something that is “derived” from the part to be replaced
[英]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.