如何使用正则表达式在html文件中仅选择内联样式?

时间:2017-01-18 08:30:11

标签: regex

我尝试仅在p标签和div标签中选择内联样式。但无需选择td,内联样式

正则表达式style=[\"\w\d\.\:\-\'\s\#\;]+

输入:

<p class="Test"><span style="font-family:Verdana">?</span><span style="font:7.0pt 'Times New Roman'">&#xa0; </span><span>AAA</span></p>

<table cellspacing="0" cellpadding="0" style="border-collapse:collapse; margin-left:0pt">
<tr>
<td style="border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt">
<p class="Tabelle" style="margin-top:3pt; margin-bottom:3pt"><span style="font-family:Tahoma; font-size:9pt">Detail</span></p>
</td>

输出:

p标签中的

style="margin-top:3pt; margin-bottom:3pt

注意: 我只需要选择p标签,div标签内联样式。

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

查找:

(<(?:p|div)[^<]*)(style="[^"]*")([^>]*>)

替换为:

$1$3

C#代码示例:

using System;
using System.Text.RegularExpressions;
public class Test
{
    public static void Main()
    {
        string pattern = @"(<(?:p|div)[^<]*)(style=""[^""]*"")([^>]*>)";
        string substitution = @"$1$3";
        string input = @"<p class=""Test""><span style=""font-family:Verdana"">?</span><span style=""font:7.0pt 'Times New Roman'"">&#xa0; </span><span>AAA</span></p>

<table cellspacing=""0"" cellpadding=""0"" style=""border-collapse:collapse; margin-left:0pt"">
<tr>
<td style=""border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt"">
<p class=""Tabelle"" style=""margin-top:3pt; margin-bottom:3pt""><span style=""font-family:Tahoma; font-size:9pt"">Detail</span></p>
</td>

";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);

        System.Console.WriteLine(result);
    }
}

Explanation

您可以获得第1组中的yoru数据