2012-04-19 76 views
0

我想看看是否一個字符串1是包含字符串在Perl檢查字符串是另一個字符串的子集,加上在Perl在開始時一個小數字

$Item1="I Like Coffee"; 
$Item2="2 I Like Coffee"; 
$Item3="I like Milke"; 

$Item1=$Item2 but $Item1!=$item3 

一種方式來做到這一點是剝離在$ item2的開頭輸出2,然後進行比較。如下:

$item=~s/(\d+)//; 

然後我們可以比較一下。 相反,更好的方法是grep Item2中的Item1,如果是true,則執行其餘的操作。但是,grep只能用於列表,有沒有微妙的方法來做到這一點?謝謝!

回答

1
if (index(STRING,SUBSTRING) >= 0) and print "SUBSTRING in STRING\n" ; 
+0

這正是我一直在尋找的還有Perl中的一個SUBSTR功能以及。大! – 2012-04-19 04:01:34

1

安德烈的問題解決了部分實際問題。 index會告訴你該模式中是否存在該子字符串,但是他回答它的方式可能會返回兩個字符串完全相同的判斷。

sub majics_match { 
    my ($look, $cand) = @_; 
    return 1 unless length($look // ''); 
    return 0 unless length($cand // ''); 
    my $pos = index($cand, $look); 
    return 0 unless $pos > 0; 
    return substr($cand, 0, $pos) =~ m/^\d\s+/ 
     && substr($cand, $pos + length($look)) eq '' 
     ; 
} 

...或者你可以用正則表達式做到這一點:

$cand =~ m/^\d \Q$look\E$/; 
相關問題