2010-03-22 39 views
3

什麼C#正則表達式將取代所有這些:什麼正則表達式會從BR標籤中刪除所有屬性?

<BR style=color:#93c47d> 
<BR style=color:#fefefe> 
<BR style="color:#93c47d"> 
<BR style="color:#93c47d ..."> 
<BR> 
<BR/> 
<br style=color:#93c47d> 
<br style=color:#fefefe> 
<br style="color:#93c47d"> 
<br style="color:#93c47d ..."> 
<br> 
<br/> 

有:

<br/> 

基本上是 「從任何BR元素和小寫它刪除所有屬性」。

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – thecoop 2010-03-22 15:25:20

+0

@thecoop:這隻與實際解析HTML有關,它這個問題並不需要。在這種情況下,唯一可能破壞正則表達式的是,如果在屬性內有一個「>」,我認爲這是無效的。 – 2010-03-22 15:27:53

+0

想到這個HTML的人是誰?無法想象一個用例。 – Dykam 2010-03-22 15:29:46

回答

8

喜歡的東西:

Regex.Replace(myString, "<br[^>]*>", "<br/>", RegexOptions.IgnoreCase); 

或不IgnoreCase

Regex.Replace(myString, "<[Bb][Rr][^>]*>", "<br/>"); 
+0

很好用,謝謝! – 2010-03-22 15:23:35

0

假設你從未有過的風格之後的任何屬性,我敢打賭像

class Program 
{ 
    const string SOURCE = @"<BR style=color:#93c47d> 
<BR style=color:#fefefe> 
<BR style=""color:#93c47d""> 
<BR style='color:#93c47d'> 
<BR> 
<BR/> 
<br style=color:#93c47d> 
<br style=color:#fefefe> 
<br style=""color:#93c47d""> 
<br style='color:#93c47d'> 
<br> 
<br/>"; 

    static void Main(string[] args) 
    { 
    const string EXPRESSION = @"(style=[^""'][^>]*)|(style=""[^""]*"")|(style='[^']*')"; 

    var regex = new Regex(EXPRESSION); 

    Console.WriteLine(regex.Replace(SOURCE, string.Empty)); 
    } 
} 

你可能會如果有屬性寫入,那麼最好使用程序化解決方案ag之後的樣式屬性。

相關問題