如何使用量词访问括号中的捕获缓冲区?
#!/usr/local/bin/perl
use warnings;
use 5.014;
my $string = '12 34 56 78 90';
say $string =~ s/(?:(\S+)\s){2}/$1,$2,/r;
# Use of uninitialized value $2 in concatenation (.) or string at ./so.pl line 7.
# 34,,56 78 90
使用 @LAST_MATCH_START
和 @LAST_MATCH_END
它可以工作*,但线路太长。
不行,看TLP的回答。
*布丁的证明在于吃
并不总是正确的。
say $string =~ s/(?:(\S+)\s){2}/substr( $string, $-[0], length($-[0]-$+[0]) ) . ',' . substr( $string, $-[1], length($-[1]-$+[1]) ) . ','/re;
# 12,34,56 78 90
最佳答案
您无法访问第一个捕获组的所有先前值,只有最后一个值(或匹配结束时的当前值,如您所见)将保存在 $1
中(除非你想使用 (?{ code })
hack)。
对于您的示例,您可以使用以下内容:
s/(\S+)\s+(\S+)\s+/$1,$2,/
关于regex - 如何使用量词访问括号中的捕获缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6623969/