找到匹配项后插入一个字符串行

时间:2017-09-13 09:35:06

标签: perl scripting-language

我想编写一个脚本,在找到匹配字后插入一个字符串行。匹配词有多个出现,但我想在第二次出现时插入。如何在perl中编写脚本?

2 个答案:

答案 0 :(得分:1)

看到你的问题不清楚你的脚本必须是动态的还是静态的,以及你没有提供任何例子的事实,我只会给出一个简单的解决方案,指出你正确的方向。它将搜索单词string,然后在其后添加换行符。它还使用/g开关,因此它会对字符串中的所有string字词进行全局操作。

use strict;
use warnings;

my $str = "this is my string";
   $str=~s/string/string\nAnother string/g;
   print $str;

从这里开始,我建议你付出一些努力来做一些研究,而不仅仅是期待一切都给予。你似乎是一个perl初学者,所以为初学者搜索谷歌Perl Tutorials,以帮助你入门。

答案 1 :(得分:0)

希望我理解正确,请尝试以下

您可以使用正则表达式demo

my $s = "Stack is a linear data structure stack follows a particular order in stack the operations are performed";
$s=~s/(.*?Stack){3}\K//i;

或者您可以尝试使用substr

use warnings;
use strict;

my $match_to_insert = 2; #which match you need to insert
my $f = 1;

while($s=~m/stack/gi)
{
    substr($s,$+[0],0) = "\n" , last if($f eq $match_to_insert);
    $f++;

}

print "$s\n";

$+[0]将给出匹配字符串的索引位置,并且我正在使用该索引创建substr函数,并且我在该位置插入'\ n'。

相关问题