Perl Named Captured Group

限于喜欢 提交于 2021-02-05 11:41:33

问题


I have created two named capture variables in the regex and the second one doesn't seem to return any value while the first one can. I am not sure why..here is the code.

my $string = 'test [google] another test [windows]';

my $regex=qr/\w*\[{1}(?<firstBracket>\w+)\]{1}(?<secondBracket>\w*)/ip;

$string=~ /$regex/;

say $+{secondBracket};

I am expecting that "secondBracket" will return. I can do $+{firstBracket}, but not the second one...Can someone help please?

Thanks.


回答1:


You probably mean:

my $string = 'test [google] another test [windows]';

if( $string =~ /.*?\[(?<firstBracket>\w+)\].*?\[(?<secondBracket>\w+)\]/i ) {
        say $+{firstBracket};
        say $+{secondBracket};
}

output

google
windows

or

my $re = qr/.*?\[(?<firstBracket>\w+)\].*?\[(?<secondBracket>\w+)\]/i;
if( $string =~ $re ) {
    ...
}

with same output...



来源:https://stackoverflow.com/questions/42868125/perl-named-captured-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!