2009-05-27 47 views
0

我真的無法弄清楚如何做到這一點,我可以做相當簡單的正則表達式,但更復雜的表達式真的讓我感到困惑。什麼是REGEX在C#中的html文檔中匹配這種模式?

在特定HTML文檔中出現以下內容:

<span id="label"> 
<span> 
<a href="http://variableLink">Joe Bloggs</a> 
now using 
</span> 
<span> 
' 
<a href="/variableLink/">Important Data</a> 
' 
</span> 
<span> 
on 
<a href="/variableLink">Important data 2</a> 
</span> 
</span> 

我需要提取兩個「重要數據」點,並可能花好幾個小時的工作了正則表達式來做到這一點(我使用的.NET。 C#3.5中的正則表達式庫)

+0

我幫不了你,我很害怕,但如果你需要在.NET正則表達式的幫助,儘量快報http://www.ultrapico.com/Expresso.htm它是免費的,真的很不錯的測試正則表達式。 – 2009-05-27 11:24:20

+1

您必須使用regexp,還是可以使用HTML解析庫,如HTML Agility Pack(http://www.codeplex.com/htmlagilitypack)? – 2009-05-27 11:25:43

+0

我可以使用任何東西,不一定是正則表達式。 – 2009-05-27 11:37:42

回答

4

正如通常所說的,正則表達式通常不是解析HTML,XML和朋友的正確工具 - 考慮使用HTML或XML解析庫。如果您確實想要或必須使用正則表達式,以下內容將與許多情況下的標籤內容相匹配,但在某些情況下可能仍會失敗。

<a href="[^"]*">(?<data>[^<]*)</a> 

這個表達式匹配不開始http://各個環節 - 這是唯一的區別obviouse我可以鏈接之間看到。

<a href="(?!http://)[^"]*">(?<data>[^<]*)</a> 
0

查找.NET的後視和前瞻語法,並使用它查找HTML中的錨定標記。 This site可能會幫助你。作爲正則表達式的替代方法,您可以考慮使用System.Xml.XPath.XPathNavigator來直接尋址這些節點。

0

我正則表達式是有點生疏,但沿着以下信息可能有助於線的東西(雖然它可能會需要一些微調):

(?<=\<a href="/variableLink[/]?"\>)(.*)+(?=</a>) 
0
<a\shref.*?"/variableLink/?">(.*)</a> 

一組包含錨的名稱。經過Expresso測試。適用於您提供的示例文本。
更新:也適用於Snippy。

Regex regex = new Regex(@"<a\shref.*?""/variableLink/?"">(.*)</a>", RegexOptions.Multiline); 
foreach (Match everyMatch in regex.Matches(sText)) 
{ 
    Console.WriteLine("{0}", everyMatch.Groups[1]); 
} 

輸出:下面

Important Data 
Important data 2 
4

使用HtmlAgilityPack。它在「標籤」ID內的第二或更後的鏈接中打印任何文本。當然,修改XPath執行一些不同的操作相對簡單。

HtmlDocument doc = new HtmlDocument(); 
    doc.Load(new StringReader(@"<span id=""label""> 
<span> 
<a href=""http://variableLink"">Joe Bloggs</a> 
now using 
</span> 
<span> 
' 
<a href=""/variableLink/"">Important Data</a> 
' 
</span> 
<span> 
on 
<a href=""/variableLink"">Important data 2</a> 
</span> 
</span> 
")); 
    HtmlNode root = doc.DocumentNode; 

    HtmlNodeCollection anchors; 
    anchors = root.SelectNodes("//span[@id='label']/span[position()>=2]/a/text()"); 
    IList<string> importantStrings; 
    if(anchors != null) 
    { 
     importantStrings = new List<string>(anchors.Count); 
     foreach(HtmlNode anchor in anchors) 
     importantStrings.Add(((HtmlTextNode)anchor).Text); 
    } 
    else 
     importantStrings = new List<string>(0); 

    foreach(string s in importantStrings) 
     Console.WriteLine(s); 
相關問題