簡體   English   中英

將正則表達式存儲在變量中,然后找到pattern(Perl)?

[英]Storing Regular Expression in variable and then finding pattern(Perl)?

嗨,我在Perl中遇到了正則表達式問題。 如果我將正則表達式存儲在perl中的變量中,將無法匹配。 為什么這樣呢? 我該如何解決這個問題? 下面是我的代碼,輸出失敗作為輸出:

my $str1 = 'abc..';
my $str2 = 'abcde';

my $pcode = $str1;

print $pcode;

if( $pcode =~ /$str2/)
{
    print "Got";
}
else
{
    print "Failed";
}

您需要顛倒邏輯。 正則表達式放在//而不是字符串中。

給變量起個更好的名字,當你這樣顛倒邏輯時,它就會變得更加明顯。

my $pattern = 'abc..';
my $string = 'abcde';

if ($string =~ /$pattern/) {
    print "Got";
} else {
    print "Failed";
}

您的if( $pcode =~ /$str2/)順序錯誤。 您需要更改它:

if( $str2 =~ /$pcode/)

基本上, $pcode包含模式,因此它位於//內,而您要對照模式檢查的字符串位於=~前面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM