文本中多次出现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
的东西,但就是无法达成解决方案。
这对我来说似乎有点复杂;有什么帮助吗?提前谢谢:-)