2011-11-23 183 views
3

提取IMG源我有一個字符串是這樣的:正則表達式從字符串

<img width="1" height="1" alt="" src="http://row.bc.yahoo.com.link"> 

我應該有什麼正則表達式在C#寫提取它的SRC部分? (最終結果應該是「http://row.bc.yahoo.com.link」)

+0

你到現在爲止有什麼想法? –

回答

4

如果你正在處理HTML,你最好使用HTML分析器,如HTML Agility Pack

樣品:

var doc = new HtmlDocument(); 

doc.LoadHtml(
    "<img width=\"1\" height=\"1\" alt=\"\" src=\"http://row.bc.yahoo.com.link\">"); 

var anchor = doc.DocumentNode.Element("img"); 

Console.WriteLine(anchor.Attributes["src"].Value); 

更新: 如果您已經使用HTML敏捷性包,並選擇從文檔使用XPath需要迭代它們並訪問所有img標籤src屬性:

var imgs = doc.DocumentNode.SelectNodes("//img/@src"); 

foreach (var node in imgs) 
{ 
    Console.WriteLine(node.Attributes["src"].Value); 
} 
+0

我使用Agillity Pack並使用XPath選擇匹配// img/@ src的節點。但一旦我有,我想從該節點提取src。我不能這樣做,但正則表達式。 – Ghita

+0

你說得對,沒有必要使用正則表達式,因爲我已經有了使用Agillity Pack獲得的節點。 – Ghita

3

此模式應該工作:src="([^"]*)"

+0

它的工作原理,但使用HTML敏捷包時提供的解決方案是最好的。 Tnx – Ghita