[英]How to capture multiple regex groups separated by logical AND inside an if statement in perl?
Here is the code -这是代码 -
my $s_ver = 'port=":443"; d=3600; v="10,20"';
my $b_ver = 'FB10';
if ($s_ver =~ /(v="[0-9]+(,[0-9]+)*")/ && $b_ver =~ /FB(\d\d)/){
{
print("$1 and $2\n");
}
Current Output - 10 and
当前 Output - 10 and
Expected output - v="10,20" and 10
预期 output - v="10,20" and 10
How can this be achieved?如何做到这一点? Thanks.谢谢。
if (
( my ($s_cap) = $s_ver =~ /(v="[0-9]+(?:,[0-9]+)*")/ ) &&
( my ($b_cap) = $b_ver =~ /FB(\d\d)/ )
) {
print("$s_cap and $b_cap\n");
}
You should usually never try to retain and use the $number variables over long code distances.您通常不应该尝试在较长的代码距离上保留和使用 $number 变量。 Long meaning 2 or 3 lines.长表示 2 或 3 行。 You should always capture them to normal variables immediately.您应该始终立即将它们捕获为正常变量。 The reason is obvious from your attempt at subverting that wisdom.从你试图颠覆这种智慧的尝试中可以看出原因。
Your attempt can't work because the $num match variables are localized and lexically scoped.您的尝试行不通,因为 $num 匹配变量是本地化的并且是词法范围的。 One sucessful match clobbers any previous one.一场成功的比赛会击败之前的任何一场比赛。 However a failed match does not reset them.但是,失败的匹配不会重置它们。 Caveat emptor.买者自负。
There are machinations you can do to get your two regex tests into a single if
but it's just not worth it.您可以采取一些措施将两个正则表达式测试合并到一个if
中,但这并不值得。
Do this instead.改为这样做。
my $s_ver = 'port=":443"; d=3600; v="10,20"';
my $b_ver = 'FB10';
my $s_match = $s_ver =~ m/(v="[0-9]+(?:,[0-9]+)*")/ ? $1 : undef;
my $b_match = $b_ver =~ m/FB(\d\d)/ ? $1 : undef;
if ( defined $s_match and defined $b_match ) {
print("$s_match and $b_match\n");
}
HTH HTH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.