Regex 使用grep查找匹配的字符串不会返回匹配的值
我使用下面的代码从perl中的grep函数中获取匹配值,但它总是返回值1,而不是返回匹配值Regex 使用grep查找匹配的字符串不会返回匹配的值,regex,perl,Regex,Perl,我使用下面的代码从perl中的grep函数中获取匹配值,但它总是返回值1,而不是返回匹配值 use strict; use warnings; my @capture = "err=\"some value\""; if(my @matched_string = (grep(/\berr\b/, @capture) || grep(/\bwarn\b/, @capture))){ print "@matched_string"; } 如何获得匹配的值 OR(|)在第一个(
use strict;
use warnings;
my @capture = "err=\"some value\"";
if(my @matched_string = (grep(/\berr\b/, @capture) || grep(/\bwarn\b/, @capture))){
print "@matched_string";
}
如何获得匹配的值 OR(|
)在第一个(左)调用上施加标量上下文。因此,它返回匹配的次数,然后对其求真。若它与任何内容匹配,那个么该数字的计算结果为true,所以该数字由|
返回。否则,您将得到另一个列表,如果该列表也没有匹配项,则会得到一个空列表
我认为您希望从@capture
获取所有带有err
的行,或者,如果完全不存在,则所有行都带有warn
。为此,您可以先对err
进行完整检查,然后查找warn
。简单的方法
my @matched_string = grep { /\berr\b/ } @capture;
@matched_string = grep { /\bwarn\b/ } @capture if not @matched_string;
但是,如果您只是希望@capture
中的所有字符串都包含err
或warn
单词,那么
my @matched_string = grep { /\b(?:err|warn)\b/ } @capture;
如果以上猜测不正确,请澄清目的。如果我只使用@matched_string=(grep(/\berr\b/,@capture),它可以很好地工作,我可以用@matched_string=(grep(/\berr\b | | b/,@capture)替换上面的表达式吗@SudhirMishra好的,是的——但这将为您提供
@capture
中包含err
或warn
单词的所有字符串。这就是您想要的吗?@SudhirMishra我将其添加到了答案中,如果不是您的意思,请告诉我。
#Perform the assignment first then do the "or" as follows
#or combine the regex to achieve what you are trying to achieve:
use strict;
use warnings;
my @capture = "err=\"some value\"";
my @matched_string;
if ((@matched_string = grep(/\berr\b/, @capture)) || (@matched_string = grep(/\bwarn\b/, @capture)) ) {
print "@matched_string";
}
#Another alternative (combining the regex)
use strict;
use warnings;
my @capture = "warn\"some value\"";
if ((my @matched_string = grep(/\b(err|warn)\b/, @capture))) {
print "@matched_string";
}