0

我有一个 xml 文件和一些替换 xml 文件的替换检查列表。如何转义正则表达式并替换该 xml 文件。只是我尝试了这个概念,但它不能完美地工作......我该怎么做?

我试过了:

输入xml:

<xml>
<p class="text">The <em type="italic">end</em> of the text</p>
<p class="text">The <bold type="strong">end of the</bold> text</p>
<p class="text">The end of <samll type="caps">the<small> text</p>
</xml>

脚本:

use strict;
open(IN, "xml_file.xml") || die "can't open $!";
my $text = join '', <IN>;
my @ar = '';
my $testing;
foreach my $t (<DATA>){
    @ar = split /\t/, $t;
    chomp($ar[0]);
    chomp($ar[1]);
    $text =~ s/$ar[0]/$ar[1]/segi;
}
print $text;

__END__
<p([^>]+)?> <line>
<small([^>]+)?> <sc$1>
<bold type=\"([^"]+)\"> <strong act=\"$1\">
<(\/)?em([^>]+)?>   <$1emhasis$2>

需要输出:

<xml>
<line>The <emhasis type="italic">end</emhasis> of the text</line>
<line>The <strong act="strong">end of the</strong> text</line>
<line>The end of <sc type="caps">the<sc> text</line>
</xml>

如何将此标记正则表达式替换为清单以及如何从组模式中获取价值..

4

2 回答 2

1

参考旧的 SO 帖子,您需要使用双重评估替换。

我不能让它工作使用<DATA>,但下面的代码会工作。您可以根据需要制作@replace 结构,我只是创建了一个简单的结构。

my $text = <<XML;
<xml>
<p class="text">The <em type="italic">end</em> of the text</p>
<p class="text">The <bold type="strong">end of the</bold> text</p>
<p class="text">The end of <small type="caps">the</small> text</p>
</xml>
XML

my @replace = (
    {
        'select' => '<p([^>]+)?>',
        'replace' => '"<line$1>"'
    },
    {
        'select' => '/p>',
        'replace' => '"/line>"'
    },
    {
        'select' => '<small([^>]+)?>',
        'replace' => '"<sc$1>"'
    },
    {
        'select' => '/small>',
        'replace' => '"/sc>"'
    },
    {
        'select' => '<bold\s+type="(.+?)".*?>',
        'replace' => '"<strong act=\"$1\">"'
    },
    {
        'select' => '/bold>',
        'replace' => '"/strong>"'
    },
    {
        'select' => '<em([^>]+)?>',
        'replace' => '"<emhasis$1>"'
    },
    {
        'select' => '/em>',
        'replace' => '"/emhasis>"'
    },
);

map {my $re = $_; $text =~ s/$re->{select}/$re->{replace}/sigee;} @replace;

print $text;
于 2013-07-03T07:23:01.337 回答
0

只需添加:

$ar[0] = qr/$ar[0]/;

就在执行正则表达式替换之前;

另外,您忘记了这种模式:

</p>    </line>

您在输入 xml 中有错字:

<samll type="caps">

应该

<small type="caps">

最后,一条建议:用正则表达式解析 XML 不是一个好主意。我推荐使用来自 CPAN 的 XML 解析器,这是一个更好的选择 (IMO)。

于 2013-07-03T06:53:39.867 回答