1

我有一段 html 代码,我想删除一些样式部分,我知道我需要正则表达式,但我不知道如何生成正则表达式,甚至不知道如何在我的 c# 代码中应用它。以下是原始字符串的示例:

<p style="color: #000000; text-transform: none; letter-spacing: normal; font-size: 12px; font-style: normal; font-variant: normal; font-weight: normal; word-spacing: 0px; white-space: normal; font-size-adjust: none; font-stretch: normal; -webkit-text-stroke-width: 0px;">

这是我希望在替换操作后得到的输出:

<p> 

我想摆脱 style 属性。我需要为所有出现的<p ...>

有很多关于这类工作的例子,但我真的对此感到困惑。所以任何关于解决方案的线索都会很棒。提前致谢。

4

2 回答 2

3

你真的找到了一个正则表达式教程(例子)来学习匹配是如何工作的,那么替换会更容易......

string output = Regex.Replace(input, @"(?<=<p)[^>]+", "");

演示

要仅删除样式属性,您也许可以使用:

string output = Regex.Replace(input, @"(?<=<p)\s*style=""[^""]+""", "");

<p请注意,如果 style 属性紧跟在(带有任意数量的空格)之后,这将不起作用。

更新了演示


要删除 html 中任何位置的属性样式,您也许可以使用(可能比前一个安全一点):

string output = Regex.Replace(input, @"(?<=<p)([^>]*?)\s*style=""[^"">]+""", "$1");

重新更新了演示

于 2013-08-14T09:33:20.307 回答
0

不知道如何在 c# 中执行此操作,但使用 bash 正则表达式中的一般示例,我会这样做:

echo "$pattern" | sed -r 's/(<p).*(>)/\1\2/'

在哪里:

(<p) ----- Captures the opening bracket with p
.*   ----- Anything inbetween up to the next ">"
()   ----- Captures the closing bracket
\1\2 ----- Gives you back the two captured things, 
           in this order, with no space inbetween

希望它有所帮助,但同样,您需要自己查找在 c# 中的替换。

于 2013-08-14T09:35:17.960 回答