2010-03-22 58 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之后的样式属性。

相关问题