需要替换文本文件各行中单词的多次出现
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $string2 = 'first_part';
my $string3 = 'middle_part';
my $string4 = 'last_part';
my @contents=();
tie @contents, 'Tie::File','test.html' or die "Not able to Tie test.html\n";
my $count=1;
foreach (@contents)
{
my $string = $_;
my $quoted_substring = quotemeta($string);
my $before = 'test_example_start';
my $after = 'text_example_end';
if ($string =~ /\Q$before\E(.*?)\Q$after\E/) {
my $finalstr = "$string2$1$string3$1$string4";
s/$quoted_substring/$finalstr/g;
print $finalstr;
}
$count++;
my $finalstr ='';
}
untie @contents;
实际字符串:
test_example_start this is lesson-1 text_example_end where everyone attended the class test_example_start this is lesson-2 text_example_end where two members attended the class test_example_start this is lesson-3 text_example_end where five members attended the class
预期结果:
first_part this is lesson-1 middle_part this is lesson-1 last_part where everyone attended the class first_part this is lesson-2 middle_part this is lesson-1 last_part where two members attended the class first_part this is lesson-1 middle_part this is lesson-3 last_part where five members attended the class
当前结果: 整个段落仅用一行代替。如下
first_part this is lesson-1 middle_part this is lesson-1 last_part
答案 0 :(得分:0)
您的问题似乎有点令人困惑。尽管您提供了“实际字符串”和“预期结果”,但要求不是很明确。
此代码应提供非常接近您想要的内容:
foldr
假设文件
let array = [
{"sales":2341,"targetMet":false,"advertisment":true},
{"sales":981,"advertisment":true},
{"sales":3423,"targetMet":true,"advertisment":false},
{..},
{..}
];
let expectedArray = array.map(({targetMet,...rest}) => {...rest});
console.log(expectedArray) // should remove all targetMet keys
的内容如下:
test_example_start这是第1课text_example_end,每个人都参加课程test_example_start这是第2课text_example_end,其中有2位成员参加了课程test_example_start这是第3课text_example_end,其中有5位成员参加了课程
然后,以上脚本的输出为:
first_part,这是第1课middle_part,这是第1课,last_part,每个人都上过课,first_part,这是第2课,middle_part,这是第2课,last_part,有两名成员参加了课程first_part,这是第3课,middle_part,这是第2课3个last_part,五个成员参加了该课程
我不确定这是否是您想要的,因为我不知道您要在新创建的#!/usr/bin/perl
use strict;
use warnings;
open FILE, "<", "test.html" or die $!;
while (my $fileline = <FILE>) {
while ($fileline =~ m/test_example_start(.*?)text_example_end(.*?)((?=test_example_start)|($))/gi) {
print "first_part$1middle_part$1last_part$2";
}
print "\n";
}
close FILE;
除了对正则表达式进行更正和代码清除外,此处的关键点在于,如果要替换所有行的出现,则应将行测试放在test.html
块中,而不是middle_part
。