簡體   English   中英

正則表達式:查找和修改多個匹配項

[英]Regex: Find and modify multiple matches

我有一個包含一些img標簽的HTML字符串。 我必須在每個img標簽中找到並修改src屬性。 例如

原始標簽為:

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

我想獲取file查詢字符串的值,將其映射到一些代碼中,獲取新名稱,並使用新名稱修改整個src屬性。

例如在給定的示例中, 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 ):       
}

有人知道如何繼續嗎? 提前致謝。

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

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);

我使用正向后視修改了您的正則表達式,因此它僅捕獲src屬性的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM