在Perl中,如何“跳过”某些文本并在剩余部分中进行搜索和替换? [复制]

2023-12-25

文本中多次出现pattern;在进行正则表达式查找和替换时,我想跳过文本的某些片段并替换pattern在剩下的部分。例如,在代码中:

#!/usr/bin/env perl
use strict;
use warnings;

#iterate the DATA filehandle
while (<DATA>) {
    # This one replaces ALL occurrences of pattern.
    s/old/new/gs;
    # How do I skip the unwanted segments and do the replace?
    #print all
    print;
}

##inlined data filehandle for testing. 
__DATA__
START xx old xx END     --> within boundaries,  should NOT replace
START xx old
      xx old xx END     --> within boundaries,  should NOT replace
// xx old               --> within comment,     should NOT replace
xx // xx old            --> within comment,     should NOT replace
. old old xx            --> following a point,  should NOT replace
                            first one, just replace second one
xx .
  old
  old xx                --> following a point,  should NOT replace first
                            one, just replace second one.
xx old xx               --> other scenarioes,   should REPLACE

编辑16.2.22(23年2月16日更新)更换/不更换的标准如下: (1)START and END可能在一行上或跨越多行,所有pattern在此范围内不应更换;

(2) . and pattern它们之间可能有也可能没有空格、制表符、换行符、第一次出现的pattern after .应更换;

(3) 注释总是以 // 开头的一行;暂时不考虑 /* ... */ 的注释风格。

(4) //可以是也可以不是一行的第一个字符;所以它是与..

START_FLAG 和 END_FLAG 之间的任何内容或评论中的任何内容都应被忽略;并且,如果pattern后面跟着一个“.”,它也应该被忽略。pattern文本其余部分中的 s 应替换为新内容。我尝试使用s/START.*?END|\/\/.*?\n|.\s*\w+|\w+//g的东西,但就是无法达成解决方案。

这对我来说似乎有点复杂;有什么帮助吗?提前谢谢:-)


使用正常的 if 语句即可:

while (<DATA>) {
  next if (m/^START/ && m/END$/ ) ||  m/^\/\// || m/^\./;
  s/old/new/gs;
  print;
}

NOTE以上是 OP 编辑​​ 16.2.22 之前的答案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Perl中,如何“跳过”某些文本并在剩余部分中进行搜索和替换? [复制] 的相关文章

随机推荐