如何在perl中匹配多行数据 [英] How to match multiline data in perl

查看:76
本文介绍了如何在perl中匹配多行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题指的是

如何在 sed 中使用 greedy 方法替换文本?

我必须匹配文件中的多行数据,并且需要使用 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 =~/&lt;strong&gt;(.*?)\n(\s)*&lt;\/strong&gt;/)
      {
          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/\&lt;strong&gt;(.*?)&lt;\/strong&gt;/<b>${1}<\/b>/gs;

print $string;

此示例使用 File::Slurp 模块一次读取整个文件.

This example uses the File::Slurp module to read in the entire file at once.

然后使用带有 gs 修饰符的正则表达式.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆