我试图在我遇到的每一行的末尾去掉评论。但是,如果在开头和结尾都注释了该行,我有兴趣保留该行。
例如:
output port_a; // comments remove this port
如果我使用这个正则表达式$line =~ s/\/{2,}.*?$//;
,注释将被正确删除,只产生我想用于进一步处理的模式,即:
output port_a;
但是,可能会发生在开头注释一行的情况:
// output port_a; // comments remove this port
在这种情况下,我想保留行首的注释,但删除行尾的注释。
// output port_a;
使用相同的正则表达式$line =~ s/\/{2,}.*?$//;
会删除所有内容!
我试过使用,s/\/{2,}[^\/]+$//g
但这并没有去除其中有斜杠的注释,这是不正确的:
// output port_a; // comments read/write
/
在开头允许一个可选,如果有则删除尾随注释
s|^\s*/?.+?\K//.*||g;
的+
需要,而不是一个量词*
所以不匹配唯一注释行。
The\K
是lookbehind 的一种形式,零宽度断言它之前的模式确实存在(它不消耗任何东西)。它还会丢弃之前的所有匹配项,因此我们不必捕获它们并将它们放回原处。这也允许\K
处理可变长度模式。
使用所示示例进行测试
use warnings;
use strict;
use feature 'say';
my @tests = (
'output port_a; // comments remove this port',
'// output port_a; // comments remove this port',
'// output port_a; // comments read/write'
);
for (@tests)
{
s|^\s*/?.+?\K//.*||gx;
say;
}
输出
输出端口_a; // 输出端口_a; // 输出端口_a;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句