2011-09-25 21 views
2

我有一些網站源流我想解析。我目前的正則表達式是這樣的:簡單的正則表達式幫助使用C#(包括正則表達式模式)

Regex pattern = new Regex (
@"<a\b    # Begin start tag 
    [^>]+?    # Lazily consume up to id attribute 
    id\s*=\s*['""]?thread_title_([^>\s'""]+)['""]? # $1: id 
    [^>]+?    # Lazily consume up to href attribute 
    href\s*=\s*['""]?([^>\s'""]+)['""]?    # $2: href 
    [^>]*    # Consume up to end of open tag 
    >     # End start tag 
    (.*?)           # $3: name 
    </a\s*>   # Closing tag", 
RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); 

但它不再匹配鏈接。我包括一個樣本字符串here

基本上我試圖匹配這些:

<a href="http://visitingspain.com/forum/f89/how-to-get-a-travel-visa-3046631/" id="thread_title_3046631">How to Get a Travel Visa</a> 

"http://visitingspain.com/forum/f89/how-to-get-a-travel-visa-3046631/" is the **Link** 
304663` is the **TopicId** 
"How to Get a Travel Visa" is the **Title** 

在我張貼的樣本中,有至少3個,我沒算其他的。

此外,我使用RegexHero(在線和免費)在添加到代碼之前交互式地查看我的匹配。

+1

使用HtmlAgilityPack。 – SLaks

+0

@Joan Venge作爲參考:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – 2011-09-25 04:40:51

+0

感謝pst,還沒有見過那一個。 –

回答

4

爲了完整起見,在這裏如何完成Html Agility Pack這是一個健壯的HTML解析器的.Net(也可通過NuGet,因此安裝它需要大約20秒)。

加載文檔,解析它,並找到3個環節是簡單的:

string linkIdPrefix = "thread_title_"; 
HtmlWeb web = new HtmlWeb(); 
HtmlDocument doc = web.Load("http://jsbin.com/upixof"); 
IEnumerable<HtmlNode> threadLinks = doc.DocumentNode.Descendants("a") 
           .Where(link => link.Id.StartsWith(linkIdPrefix)); 

就是這樣,真的。現在您可以輕鬆獲取數據:

foreach (var link in threadLinks) 
{ 
    string href = link.GetAttributeValue("href", null); 
    string id = link.Id.Substring(linkIdPrefix.Length); // remove "thread_title_" 
    string text = link.InnerHtml; // or link.InnerText 
    Console.WriteLine("{0} - {1}", id, href); 
} 
+0

謝謝Kobi,我現在就試試這個。 –

1

Don't do that(好吧,almost,但它不適合每個人)。 Parsers是爲了那種類型的東西。

+2

謝謝,但我需要一個quickfix,而不是一個重大的變化。除此之外,這是一款無人使用的個人工具。我還看到許多生產代碼中類似實踐的實例,所以我認爲即使大多數程序員也不遵循這些良好實踐。 –

3

這是很簡單的,標記變了,現在的href屬性id之前出現:

<a\b    # Begin start tag 
    [^>]+?    # Lazily consume up to href attribute 
    href\s*=\s*['""]?([^>\s'""]+)['""]?    # $1: href 
    [^>]+?    # Lazily consume up to id attribute 
    id\s*=\s*['""]?thread_title_([^>\s'""]+)['""]? # $2: id 
    [^>]*    # Consume up to end of open tag 
    >     # End start tag 
    (.*?)           # $3: name 
    </a\s*>   # Closing tag 

需要注意的是:

  • 這主要是爲什麼這是一個壞主意。
  • 組數已更改。您可以使用命名組代替而不是([^>\s'""]+)
  • 的報價仍然逃脫(這應該是字符集OK)上regex hero

例。

+0

謝謝你,在你的例子鏈接,它被修改?當我打開它時,它說0個匹配。 –

+0

@Joan - 再試一次,它沒有在鏈接上工作。 – Kobi

+0

謝謝,我剛剛嘗試過,但仍然是0比賽。 –