在文本文件中进行正则表达式查找和替换时,我想跳过并忽略文本的某些片段。也就是说,应该将文本的某些部分排除在搜索之外,而只对其余部分进行搜索和替换。标准是:
(1) 任何介于START
and END
应从搜索和替换中排除。START
可能位于也可能不位于行的开头;END
可能位于也可能不在行尾;
一对START
& END
可以跨越多条线;
(2) 内嵌注释中的任何内容//
应该被忽略;//
可能位于也可能不在行首;
(3) 之后的第一个词.
应该被忽略;.
可能位于也可能不位于行的开头;
该词可能紧随其后.
或者用空格、换行符、制表符来分割它们。
示例代码:
#!/usr/bin/env perl
use strict;
use warnings;
$/ = undef;
#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__
xx START xx old xx END xx --> ignore
xx old xx --> REPLACE !
START xx old --> ignore
xx old xx END --> ignore
xx old xx --> REPLACE !
// xx old --> ignore
xx // xx old --> ignore
xx . old old xx --> ignore first one, replace second one
.
old --> ignore
(old) xx --> REPLACE !
xx old xx --> REPLACE !
预期输出是:
xx START xx old xx END xx --> ignore
xx new xx --> REPLACE !
START xx old --> ignore
xx old xx END --> ignore
xx new xx --> REPLACE !
// xx old --> ignore
xx // xx old --> ignore
xx . old new xx --> ignore first one, replace second one
.
old --> ignore
(new) xx --> REPLACE !
xx new xx --> REPLACE !
有人可以帮我解决这里的正则表达式吗?几个小时前我发布了一个类似的问题,但该帖子充满了歧义,无法给出明确的答案。希望这篇文章可能是一个“好”且“明确”的问题。
您可以使用(*SKIP)(*F) verbs http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs跳过某事。
(?:(?s:START.*?END)|\/\/.*|\.\s*\w+\b)(*SKIP)(*F)|old
它的工作原理如下:(?:part 1 to skip|part 2 to skip|...)(*SKIP)(*F)
|
part to match
-
(?:
打开一个非捕获组 https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group交替使用(?s:
with s
flag http://www.regular-expressions.info/modifiers.html使点匹配换行符
-
\w
匹配一个单词字符 http://www.regular-expressions.info/shorthand.html [A-Za-z0-9_]
-
\b
匹配一个字边界 http://www.regular-expressions.info/wordboundaries.html
请参阅 regex101 上的演示 https://regex101.com/r/yI0jH2/3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)