如何在给定的 $start-$end 范围内执行搜索和替换? [英] How to perform search-and-replace within given $start-$end ranges?

查看:38
本文介绍了如何在给定的 $start-$end 范围内执行搜索和替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,一个文本文件有很多 $start-$end 对,每对中都有一些文本.我希望 Perl 用 $start-$end 对查找并替换所有 $pattern ;如果 $pattern 不在该对中,则不要替换它.例如对于文本:

Say, a text file have many $start-$end pairs, and within each pair there are some text. I want Perl to find-and-replace all $patterns with the $start-$end pairs; if the $pattern lies out of the pair, then don't replace it. eg for text:

xx START xx bingo xx bingo xx END xx bingo xx START xx bingo xx END bingo

文本中的任何地方都可能有换行符(此处未显示);$pattern 可以在一对中出现多次.预期结果是:

There might be newlines anywhere in the text (not shown here); $pattern may appear multiple times within a pair. Expected result is:

xx START xx okyes xx okyes xx END xx bingo xx START xx okyes xx END bingo

这项工作看起来很简单,但我只是想不出 Perl 正则表达式来完成它.有人能帮忙吗?

The job seems straightforward but I just do not figure out a Perl regex to do it. Can anyone help with this?

推荐答案

最终使用以下代码来实现我的意图:

Eventually used following code to accomplish what I intended:

$_ = "xx START xx bingo xx bingo xx END xx bingo xx START xx bingo xx END bingo";
print;
print "\n";
$_ =~ s/START.*?END/($s=$&) =~ s,bingo,okyes,g; $s/ge;
print;

这是一个单正则表达式解决方案,使用 s///g 正则表达式中的嵌入表达式和嵌套的 s///g 正则表达式.

This is a one-regex solution, using embedded expression in s///g regex, and nested s///g regexes.

抱歉这篇迟到的帖子,但我非常感谢@Sobrique、@Borodin 和@choroba 的回复,这些回复很有启发性和帮助.

Sorry for this late post, but I deeply appreciate the replies by @Sobrique, @Borodin and @choroba, which are enlightening and helpful.

这篇关于如何在给定的 $start-$end 范围内执行搜索和替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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