2014-03-14 31 views
0

我有一個HTML字符串,其中包含一些img標籤。我必須在每個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):  
} 

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

回答

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

我使用正回顧後發所以它抓住SRC屬性只有內容修改你的正則表達式。

+0

**謝謝你**正常工作 –