2010-04-22 57 views
0

我有一個簡單的要求,在HTML中提取文本。假設HTML是使用正則表達式提取HTML的部分

 
<h1>hello</h1> ... <img moduleType="calendar" /> ...<h2>bye</h2> 

我想把它轉換成三個部分

 
<h1>hello</h1> 
 
<img moduleType="calendar" /> 
 
<h2>bye</h2> 

目的是兩類,簡單的HTML和特殊標籤來提取文本與< IMG moduleType = 「日曆」。

+0

/我嘆了口氣......另一個「如何解析HTML與正則表達式」的問題... – 2010-04-22 19:11:43

+0

你在什麼語言編碼?有可能比正則表達式更好的解決方案,許多語言都有DOM解析器。另外,您可能想要接受其他一些問題的答案,以提高未來答案的質量和數量。 – 2010-04-22 19:12:34

+5

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-04-22 19:16:37

回答

0

這取決於您使用的語言和上下文。我在CMS上做了類似的事情,我的方法是首先查找標籤,然後查找屬性。

獲取廣告代碼

"<img (.*?)/>" 

然後,我通過結果搜索如果你想找到的所有屬性,你可以很容易改變的明確所有權,正則表達式[AZ]針對特定屬性

'title="(.*?)"' 

,或非空白字符,然後遍歷這些結果。

+0

對抗downvotes你會得到 - 歡迎來到SO; - )在答案中包含已知問題/限制。使用正則表達式進行HTML解析幾乎總是被禁止的。 – 2010-04-22 20:02:29

0

我實際上試圖做類似的事情,因爲asp.net編譯器將標記編譯成服務器控件樹,正則表達式被asp.net編譯器大量使用。我有一個臨時解決方案,雖然不好,但似乎沒問題。

 
//string source = "<h1>hello</h1>"; 
string source = "<h1>hello<img moduleType=\"calendar\" /></h1> <p> <img moduleType=\"calendar\" /> </p> <h2>bye</h2> <img moduleType=\"calendar\" /> <p>sss</p>"; 
Regex exImg = new Regex("(.+?)(<img.*?/>)"); 

var match = exImg.Match(source); 
int lastEnd = 0; 
while (match.Success) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
    Console.WriteLine(match.Groups[2].Value); 
    lastEnd = match.Index + match.Length; 
    match = match.NextMatch(); 
} 
Console.WriteLine(source.Substring(lastEnd, source.Length - lastEnd));