Ωme*_*ega 1 regex perl parsing
在Perl正则表达式中,我如何打破/ ge循环..?
假设代码是:
s/\G(foo)(bar)(;|$)/{ break if $3 ne ';'; print "$1\n"; '' }/ge;
Run Code Online (Sandbox Code Playgroud)
...... break这里不起作用,但它应该说明我的意思.
一般来说,我会把它写成一个while声明:
while( s/(foo)(bar)/$1/ ) {
# my code to determine if I should stop
if(something) {
last;
}
}
Run Code Online (Sandbox Code Playgroud)
使用此方法的警告是,您的搜索/替换将在每次开始时开始,这可能会取决于您的正则表达式.
如果您真的想在正则表达式中执行此操作,则可以编写一个函数,如果到达终点,则返回未修改的字符串,例如在这种情况下计数:
my $count=0;
sub myfunc {
my ($string, $a, $b) = @_;
$count++;
if($count > 3) {
return $string;
}
return $a;
}
$mystring = "foobar foobar, foobar + foobar and foobar";
$mystring =~ s/((foo)(bar))/myfunc($1,$2,$3)/ge;
# result: $mystring => "foo foo, foo + foobar and foobar"
Run Code Online (Sandbox Code Playgroud)
如果我知道你的具体情况,我可能会提供一个更有用的例子.