使用PERL正则表达式替换删除一个HTML表而不是另一个HTML表

时间:2012-07-20 06:12:46

标签: regex perl

我还在学习PERL,所以你能提供的任何帮助都会非常感激。我确信我正在查看的问题有一个简单的答案,但我不确定我能弄明白。在此先感谢您的帮助!

我的txt文件中包含一堆HTML代码。我想删除许多HTML表。但是,我想保留一对。这些表,即守护者,在其中有特定的词。

让我们说$ txt代表文本文件

$txt = "<TABLE> The brown dog runs </TABLE> 
        Here is another animal 
        <TABLE> The black cat walks </TABLE> 
        Here is another animal
        <TABLE> The Orange snake slithers </TABLE> 
        Here is another animal   
        <TABLE> Green lizard crawls </TABLE> 
        Here is another animal 
        <TABLE> The brown bird flys </TABLE> 
        Here is another animal          
        <TABLE> The green duck flys </TABLE> 
        Here is another animal";

我想保留任何有棕色动物飞行动物的桌子。我不想保留任何其他表格。 (我想保留第1,第5和第6桌并摆脱其余部分)。因此,如果表中有褐色单词,或者如果单词为flys,则保留表格,如果没有,则删除表格。

我已经使用以下正则表达式来删除其他情况下的表,但这将删除所有表。

$txt =~ s{(<Table>.*?)(</Table>)}{table_was_here}ismog;

我如何修改此代码以保留包含某些文本字符串的表?

再次感谢!

2 个答案:

答案 0 :(得分:0)

将其更改为:

$txt =~ s{(<Table>.*?(brown|flys).*?(</Table>)}{table_was_here}ismog;

(小注意,正确的拼写是“苍蝇”,而不是“飞行”)

答案 1 :(得分:0)

以下两项都有效:

$txt =~ s{<TABLE>.*?</TABLE>}{$_ = $&; /brown|flys/ ? $_ : ''}isge;

for ( $txt =~ m{<TABLE>.*?</TABLE>}isg ) {
    $txt =~ s/$_// if !/brown|flys/;
}

两者的输出:

<TABLE> The brown dog runs </TABLE> 
Here is another animal 

Here is another animal

Here is another animal   

Here is another animal 
<TABLE> The brown bird flys </TABLE> 
Here is another animal          
<TABLE> The green duck flys </TABLE> 
Here is another animal

希望这有帮助!