简体   繁体   English

如何重复 Perl 正则表达式直到没有任何更改?

[英]How can I repeat a Perl Regular Expression until no changes are left?

I'm trying to write a simple command line script to fix some whitespace and need to replace occurrences of two spaces with a tab, but only if it appears at the beginning of the line (prefixed only by other tabs.)我正在尝试编写一个简单的命令行脚本来修复一些空格,并且需要用制表符替换出现的两个空格,但前提是它出现在行首(仅以其他制表符为前缀。)

I came up with s/^(\\t*) /\\1\\t/g;我想出了s/^(\\t*) /\\1\\t/g; which works perfectly if I run through multiple passes, but I don't know enough about perl to know how to loop until the string didn't change, or if there is a regular expression way to handle it.如果我通过多次传递,它可以完美地工作,但我对 perl 了解得不够多,无法知道如何循环直到字符串没有改变,或者是否有正则表达式方式来处理它。

My only thought was to use a lookbehind but it can't be variable length.我唯一的想法是使用后视,但它不能是可变长度。 I'd be open to a non-regex solution if its short enough to fit into a quick command line script.如果非正则表达式解决方案足够短以适应快速命令行脚本,我会接受它。

For reference, the current perl script is being executed like so:作为参考,当前的 perl 脚本是这样执行的:

perl -pe 's/^(\t*)  /$1\t/g'

Check a very similar question .检查一个非常相似的问题

You could use 1 while s/^(\\t*) /$1\\t/g;你可以使用1 while s/^(\\t*) /$1\\t/g; to repeat the pattern until there are no changes left to make.重复该模式,直到没有任何更改为止。

或者

perl -pe 's{^(\t*)((  )+)}{$1 . "\t" x (length($2)/length($3))}e'

支持混合空格和制表符:

perl -pe'($i,$s)=/^([ \t]*)([.*])/s; $i=~s/  /\t/g; $_="$i$s";'

This is Perl, so you don't have to do a loop.这是 Perl,因此您不必执行循环。 Instead you could just evaluate in the replace expression, like so:相反,您可以在替换表达式中进行评估,如下所示:

my $tl = 4;
s{ ( \t* ) ( [ ]* ) }
 { my $l=length( $2 ); 
   "$1" . ( "\t" x int( $l / $tl )) . ( ' ' x ( $l % $tl ))
 }ex
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM