[英]Storing Regular Expression in variable and then finding pattern(Perl)?
Hi I have problem with regular expression in Perl. 嗨,我在Perl中遇到了正则表达式问题。 If i store the regular expression in variable in perl it is not able to match. 如果我将正则表达式存储在perl中的变量中,将无法匹配。 Why its like that? 为什么这样呢? How can i resolve this issue? 我该如何解决这个问题? Below is my code which prints Failed as output: 下面是我的代码,输出失败作为输出:
my $str1 = 'abc..';
my $str2 = 'abcde';
my $pcode = $str1;
print $pcode;
if( $pcode =~ /$str2/)
{
print "Got";
}
else
{
print "Failed";
}
You need to invert your logic. 您需要颠倒逻辑。 The regex goes inside the //
, not the string. 正则表达式放在//
而不是字符串中。
Give your variables better names, and it becomes more apparent when you've inverted your logic like that. 给变量起个更好的名字,当你这样颠倒逻辑时,它就会变得更加明显。
my $pattern = 'abc..';
my $string = 'abcde';
if ($string =~ /$pattern/) {
print "Got";
} else {
print "Failed";
}
Your if( $pcode =~ /$str2/)
is in the wrong order. 您的if( $pcode =~ /$str2/)
顺序错误。 You need to change it: 您需要更改它:
if( $str2 =~ /$pcode/)
Basically, $pcode
contains the Pattern, so its inside the //
and the string which you want to check against a pattern comes in front of the =~
基本上, $pcode
包含模式,因此它位于//
内,而您要对照模式检查的字符串位于=~
前面
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.