正则表达式,如何提取分隔字符串并包含一些特殊单词?

时间:2015-09-07 00:41:23

标签: regex string find extract delimited

来自以下html脚本:

<p style="line-height:0;text-align:left">
    <font face="Arial">
        <span style="font-size:10pt;line-height:15px;">
            <br />
        </span>
    </font>
</p>
<p style="line-height:0;text-align:left">
    <font face="AR BLANCA">
        <span style="font-size:20pt;line-height:30px;">
            [designation]
        </span>
    </font>
</p>
<p style="line-height:0;text-align:left">
    &nbsp;&nbsp;
</p>

我想提取以下内容

<font face="AR BLANCA">
    <span style="font-size:20pt;line-height:30px;">
        [désignation]
    </span>
</font>

我试过这个正则表达式:

<font.*?font>

这可以分别提取两个匹配,但是如何指定我想要包含[]的那个? 谢谢

2 个答案:

答案 0 :(得分:0)

使用Html Agility Pack的方式:

using HtmlAgilityPack;
...

string htmlText = @"<p style=""line-height:0;text-align:left"">
...";

HtmlDocument html = new HtmlDocument();
html.LoadHtml(htmlText);
HtmlNode doc = html.DocumentNode;

HtmlNodeCollection nodes = doc.SelectNodes("//font[.//text()[contains(substring-after(., '['), ']')]]");

if (nodes != null)
{
    foreach (HtmlNode node in nodes)
    {
        Console.WriteLine(node.OuterHtml);
    }
}

答案 1 :(得分:-2)

通常,您不应该使用HTML正则表达式 - 通常有很多更好的方法来执行它。但是,在某些孤立的情况下,它完全正常。假设这是其中一种情况,这里是如何使用正则表达式。

当您以这种方式考虑时,制作正则表达式通常很容易:写下您想要匹配的内容,然后根据需要用正则表达式替换部分内容。

我们要匹配

lineString = cell(sizeA*sizeB, 1);
idx = 1;
for i = 1:sizeA
    for j = 1:sizeB
         lineString{idx} = [A{i},B{j}];
         idx = idx + 1;
    end
end

我们不关心<font face="AR BLANCA"> <span style="font-size:20pt;line-height:30px;"> [désignation] </span> </font> face="AR BLANCA"> <span style="font-size:20pt;line-height:30px;">désignation是什么,因此请将其替换为</span>

.*

我们还必须确保您转义所有特殊字符,否则<font .*[.*].*</font> 会被误认为是character class

[.*]

我们还希望匹配所有字符,但大部分时间<font .*\[.*\].*</font> 仅匹配非换行字符。 .是一个字符类,根据定义匹配所有字符。

[\S\s]

我们终于有了最后一个问题 - 这个正则表达式将从第一个<font [\S\s]*\[[\S\s]*\][\S\s]*</font> 到最后一个<font匹配。使用HTML示例,使量词变得懒惰对我们没有帮助,所以我们需要做其他事情。我知道的最好的方法是使用解释here的技巧。因此,我们将</font>的每个实例替换为[\S\s]*

((?!</?font)[\S\s])*

Here's an online demonstration of this regex.

相关问题