Perl中如何将匹配字符串与替换字符串存入数组?
解决Perl替换时同时记录匹配与替换内容的问题
你的核心需求是在执行正则替换时,把匹配到的字符串和对应的替换字符串都存入数组@storedContent,而不是只存匹配项对吧?原代码里只用了$&(当前匹配的内容),所以只记录了匹配的部分,我给你两种实用的实现方式:
方法一:替换时同步记录(推荐)
利用Perl正则的e修饰符,让替换表达式作为Perl代码执行,这样我们可以在替换的同时把匹配项和替换项一起push到数组里:
my @storedContent = (); my $string = "some content are stored.... <whateverfind> more text <whateverfind> end"; # 使用e修饰符,在替换逻辑中完成记录+替换 $string =~ s/<whateverfind>/ # 先把匹配项和替换项存入数组 push @storedContent, $&, '<whateverreplace>'; # 返回替换后的字符串,完成原字符串的替换 '<whateverreplace>' /egs; # 输出结果,每一行依次是匹配项、替换项 print join "\n", @storedContent;
原理说明
e修饰符允许替换右侧的内容作为Perl代码运行,而不是普通字符串$&代表当前正则匹配到的完整文本(也就是<whateverfind>)- 我们先执行
push操作把配对的内容存入数组,再返回替换字符串完成原文本的修改
方法二:先收集匹配项再生成记录
如果不需要在替换过程中实时记录,也可以先提取所有匹配项,再遍历生成对应的替换记录:
my @storedContent = (); my $string = "some content are stored.... <whateverfind> more text <whateverfind> end"; # 先提取所有匹配的内容 my @matches = $string =~ /<whateverfind>/gs; # 遍历每个匹配项,存入匹配+替换的配对内容 foreach my $match (@matches) { push @storedContent, $match, '<whateverreplace>'; } # 如果需要修改原字符串,单独执行替换 $string =~ s/<whateverfind>/<whateverreplace>/gs; # 输出结果 print join "\n", @storedContent;
两种方法都能得到你想要的输出:
<whateverfind> <whateverreplace> <whateverfind> <whateverreplace>
内容的提问来源于stack exchange,提问作者ssr1012
相关产品推荐
相关产品推荐

