如何在perl中匹配多行数据 [英] How to match multiline data in perl
问题描述
这个问题指的是
我必须匹配文件中的多行数据,并且需要使用 perl 将它们替换为其他一些文本.
I have to match multiline data in file and need to replace them with some other text using perl.
猫文件
<strong>ABC
</strong>
perl 脚本:code.pl
perl script: code.pl
#!/bin/perl
open(fh, $ARGV[0]) or die "could not open file\n";
while($input = <fh>)
{
if($input =~/<strong>(.*?)\n(\s)*<\/strong>/)
{
print($1,"\n");
}
}
close(fh);
perl 代码.pl 文件
perl code.pl file
输出:无输出
如何解决上述 pblm.
How to solve above pblm.
问候
推荐答案
use File::Slurp qw( read_file );
my $string = read_file( $ARGV[0] );
$string =~ s/\<strong>(.*?)<\/strong>/<b>${1}<\/b>/gs;
print $string;
此示例使用 File::Slurp 模块一次读取整个文件.
This example uses the File::Slurp module to read in the entire file at once.
然后使用带有 g
和 s
修饰符的正则表达式.s
允许 .*?
匹配换行符.g
使搜索全局化.全局意味着它将找到给定字符串中的所有匹配项.如果没有 g
,只会替换第一个实例.如果您希望搜索不区分大小写,您可以使用 i
正则表达式修饰符.
It then uses a regex with the g
and s
modifiers. The s
allows .*?
to match newline characters. The g
makes the search global. Global meaning it will find all matches in the given string. Without the g
only the first instance would be replaced. If you want your search to be case insensitive, you can use the i
regex modifier.
${1}
是对括号中匹配项的反向引用.
The ${1}
is a back-reference to the match in parentheses.
这个例子产生:
<b>ABC
</b>
这篇关于如何在perl中匹配多行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!