2012-09-06 16 views
2
之间的替换文本

您好我有一个名为HTML文件1.HTML这样如何使用Perl两条特定线

<div class="t_l"></div> 
<some> 
    lines 
    of 
codes 
</some> 
<div class="t_r"></div> 

我要替换的div到另一个,它存储在内容文件称为“横幅”。 横幅文件是

<other> 
    lines 
    of some 
codes 
</other> 

所以,我想的是:

<div class="t_l"></div> 
<other> 
    lines 
    of some 
codes 
</other> 
<div class="t_r"></div> 

我想出用perl是这样的:

# Slurp file 1.html into a single string 
open(FILE,"1.html") or die "Can't open file: $!"; 
undef $/; 
my $file = <FILE>; 
open(BANNER,"banner") or die "Can't open file: $!"; 
undef $/; 
my $banner = <BANNER>; 
close BANNER; 

# Set strings to find and insert 
my $first_line = '<div class="t_l"></div>'; 
my $second_line = '<div class="t_r"></div>'; 

$file =~ s/$first_line\n.+?\n$second_line#s/$first_line\n$banner\n$second_line/; 

close FILE; 

# Write output to output.txt 
open(OUTPUT,">1new.html") or die "Can't open file: $!"; 
print OUTPUT $file; 
close OUTPUT; 

上面的代码不能工作。有什么建议么?

+2

你应该使用其中之一perl HTML解析器模块,例如'HTML :: TokeParser'。 – David

+0

你真的不想用正则表达式解析HTML。那就是疯狂: - / –

回答

2

你快到了。

.的正常正则表达式行为是匹配除换行符以外的任何字符。您的正则表达式中的.+?不适用于您,因为$first_line$second_line之间有更多换行符。

使用/s修饰符告诉Perl让.也与换行符匹配。

(你也可以在你的表达外来 “#s”)

所以工作替换为:

$file =~ s/$first_line\n.+?\n$second_line/$first_line\n$banner\n$second_line/s; 
1

围棋与

$file =~ s/($first_line\n)[^\n]+(\n$second_line)/$1$banner$2/; 

$file =~ s/(?<=$first_line\n)[^\n]+(?=\n$second_line)/$banner/; 
相关问题