正则表达式:查找并修改多个匹配项

时间:2014-03-14 06:53:59

标签: c# regex c#-4.0

我有一个HTML字符串,其中包含一些img标记。我必须在每个src标记中查找并修改img属性。 e.g。

原始标签是:

<img src="http://some.domain.com/images/uncat-images/?file=vx1qro62da5th39u.jpeg&dimension=50" style="color:#2345f1" />

我希望获取file查询字符串的值,将其映射到某些代码中,获取新名称,并使用新属性修改整个src属性。

e.g。在给定示例中,file名称为vx1qro62da5th39u.jpeg。所以,我希望它从地图中找到新值。例如,它将是newfilename.png。现在我想用这个替换整个src值:

/newroot/images/newfilename.png

这意味着img应如下所示:

<img src="/newroot/images/newfilename.png" style="color:#2345f1" />

我有这个Regex,它为我提供了一个命名组中的src值:

var regex = new Regex("<img.+?src=[\\\"'](?<URL>.+?)[\\\"'].*?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);

说实话,我在这里呆了大约2个小时):

var regex = new Regex("<img.+?src=[\\\"'](?<URL>.+?)[\\\"'].*?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var html = "My html string with several img tags...";
var matches = regex.Matches(html);
foreach (Match match in matches){
     // I'm right here ):       
}

有没有人知道如何继续?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您需要使用Regex.Replace使用MatchEvaluator方法。 例如:

Regex rx = new Regex("(?<=<img[^>]*src=\")[^\"]+", RegexOptions.IgnoreCase);
string html = "My html string with several img tags...";
string newHtml = rx.Replace(html, m => "/newroot/images/" + m.Value);

我使用正面lookbehind修改了你的正则表达式,因此它只捕获 src 属性的内容。

相关问题