我是perl脚本的新手,我想删除一些可以在一行开头的字符.我想删除的字符是@和/或=
这是一个文件示例:
@word <= Remove @
=word <= Remove =
@=word <= Remove @ AND =
=@word <= Remove = AND @
=@==@=@=@@word <= Remove all the = and @
Run Code Online (Sandbox Code Playgroud)
目前,我使用substr($line, 0, 1, " ") if "@" eq substr($line, 0, 1);但它只删除了第一个@.如何编辑此行以删除所有前导@和=?
用a做这件事substr是一个很大的开销.只需使用正则表达式替换s///.
while (my $line = <DATA>) {
$line =~ s/^[@=]+//;
print $line;
}
__DATA__
@word <= Remove @
=word <= Remove =
@=word <= Remove @ AND =
=@word <= Remove = AND @
=@==@=@=@@word <= Remove all the = and @
Run Code Online (Sandbox Code Playgroud)
这里的图案是/^[@=]+/,这意味着字符串的开头_The,然后一个或多个的任一@或=.您可以使用regex101.com获取有关模式的更详细说明.它会删除它们,就像你的问题所说.
输出是:
word <= Remove @
word <= Remove =
word <= Remove @ AND =
word <= Remove = AND @
word <= Remove all the = and @
Run Code Online (Sandbox Code Playgroud)
如果你想用代码替换空格,你需要做一些更复杂的事情.
s/^([@=]+)/" "x length $1/e;
Run Code Online (Sandbox Code Playgroud)
Tanktalus建议的这个解决方案使用了/e修饰符,它允许你将Perl代码放在替换部分中s///.该x操作重复一个字符串ñ倍.我们使用它来替换整个数量@并且=一次(注意+),空字符串重复多次,因为捕获的字符串有字符.
如果您更喜欢没有/e修饰符的解决方案,请继续阅读.
1 while $line =~ s/^(\s*)[@=]/$1 /;
Run Code Online (Sandbox Code Playgroud)
我们捕获()零个或多个空格\s,并且也恰好匹配其中一个@或者=全部锚定到字符串的开头^.然后我们将其替换为$1来自的捕获()和空白.
我们将此替换作为while循环的条件运行,因为我们希望它在每次尝试后重置正则表达式引擎的位置,因为字符串的开头已经改变.该1 while 修正后的语法是写作的只是一小段路:
while ( $line =~ s/^(\s*)[@=]/$1 / ) {
# do nothing
}
Run Code Online (Sandbox Code Playgroud)
使用与上面相同的程序运行的代码输出是:
word <= Remove @
word <= Remove =
word <= Remove @ AND =
word <= Remove = AND @
word <= Remove all the = and @
Run Code Online (Sandbox Code Playgroud)
要了解为什么这样做正在做,请尝试这样做:
while (my $line = <DATA>) {
print $line;
print $line while $line =~ s/^(\s*)[@=]/$1 /;
}
Run Code Online (Sandbox Code Playgroud)
你会看到它在循环的每次迭代中是如何重新开始的1 while ....
@word <= Remove @
word <= Remove @
=word <= Remove =
word <= Remove =
@=word <= Remove @ AND =
=word <= Remove @ AND =
word <= Remove @ AND =
=@word <= Remove = AND @
@word <= Remove = AND @
word <= Remove = AND @
=@==@=@=@@word <= Remove all the = and @
@==@=@=@@word <= Remove all the = and @
==@=@=@@word <= Remove all the = and @
=@=@=@@word <= Remove all the = and @
@=@=@@word <= Remove all the = and @
=@=@@word <= Remove all the = and @
@=@@word <= Remove all the = and @
=@@word <= Remove all the = and @
@@word <= Remove all the = and @
@word <= Remove all the = and @
word <= Remove all the = and @
Run Code Online (Sandbox Code Playgroud)