[英]Perl regex: How to capture groups in piped text?
I expected the output of 我期望的输出
echo "(a b c)(a b c)" | perl -ne "/(a) b/g; print $1"
to be: 成为:
aa
since $1 refers to the first captured group, which happens to be "a". 因为$ 1指的是第一个捕获的组,恰好是“ a”。
However the above code outputs : 但是上面的代码输出:
(a b c)(a b c)
What am I doing wrong? 我究竟做错了什么?
First use single quotes under *nix, as this is not what you want: 首先在* nix下使用单引号,因为这不是您想要的:
echo "(a b c)(a b c)" | perl -MO=Deparse -ne "/(a) b/g; print $1"
LINE: while (defined($_ = <ARGV>)) {
/(a) b/g;
print $_;
}
and then use scalar context with /g
to iterate over all matches 然后使用标量上下文和/g
遍历所有匹配项
echo "(a b c)(a b c)" | perl -ne 'print $1 while /(a) b/g'
or use list context so regex returns all matches at once, 或使用列表上下文,以便正则表达式一次返回所有匹配项,
echo "(a b c)(a b c)" | perl -ne 'print /(a) b/g'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.