2011-04-14 116 views
1

我有一個類似「ab.cde.fg.hi」的字符串,我想將它分成兩個字符串。字符串匹配和提取

  1. 「ab.cde.fg」
  2. 「.hi」

怎麼辦呢?我得到了一些代碼,可以讓我獲得第二個字符串,但是如何檢索剩餘的字符?

$mystring = "ab.cde.fg"; 
$mystring =~ m/.*(\..+)/; 
print "$1\n"; 

回答

1
my ($first, $second) = $string =~ /(.*)(\..*)/; 

您還可以使用split

my ($first, $second) = split /(?=\.[^.]+$)/, $string; 
1

你確定你是不是在找...

($name,$path,$suffix) = File::Basename::fileparse($fullname,@suffixlist); 
1
my @parts = /(.*)\.(.*)/s; 

my @parts = split /\.(?!.*\.)/s; 

my @parts = split /\.(?=[^.]*\z)/s; 

更新:我誤解。 「。」應該包含在第二部分中,但它不在上面。以上應該是:

my @parts = /(.*)(\..*)/s; 

my @parts = split /(?=\.(?!.*\.))/s; 

my @parts = split /(?=\.[^.]*\z)/s; 
+0

應該提到最後兩個分割'$ _'字符串 – 2011-04-15 10:29:36

+0

@eugene y,所有6個都在'$ _'上操作,儘管可以很容易地調整所有6個以處理不同的變量。 – ikegami 2011-04-15 18:24:22

0

宣傳我的想法用RINDEX從"ab.cde.fg.hi"獲得

1) "ab.cde.fg" 
    2) ".hi" 

,我寫這個劇本,使實驗更加容易:

use strict; 
    use diagnostics; 
    use warnings; 
    use English; 

    my @tests = (
     [ 'ab.cde.fg.hi', 'ab.cde.fg|.hi' ] 
    , [ 'abxcdexfg.hi', 'abxcdexfg|.hi' ] 
); 
    for my $test (@tests) { 
    my $src = $test->[0]; 
    my $exp = $test->[1]; 
    printf "-----|%s| ==> |%s|-----\n", $src, $exp; 
    for my $op (
     [ 'ikegami 1' , sub { shift =~ /(.*)\.(.*)/s; } ] 
     , [ 'ikegami 2' , sub { split(/\.(?!.*\.\z)/s, shift) } ] 
     , [ 'rindex' , sub { my $p = rindex($_[0], '.'); 
           ( substr($_[0], 0, $p) 
           , substr($_[0], $p) 
          ); } 
     ] 
    ) { 
     my ($head, $tail) = $op->[1]($src); 
     my $res = join '|', ($head, $tail); 
     my $ok = $exp eq $res ? 'ok' : "fail: $exp expected."; 
     printf "%12s: %-20s => %-20s : %s\n", $op->[0], $src, $res, $ok; 
    } 
    } 

輸出:

-----|ab.cde.fg.hi| ==> |ab.cde.fg|.hi|----- 
    ikegami 1: ab.cde.fg.hi   => ab.cde.fg|hi   : fail: ab.cde.fg|.hi expected. 
    ikegami 2: ab.cde.fg.hi   => ab|cde    : fail: ab.cde.fg|.hi expected. 
     rindex: ab.cde.fg.hi   => ab.cde.fg|.hi  : ok 
-----|abxcdexfg.hi| ==> |abxcdexfg|.hi|----- 
    ikegami 1: abxcdexfg.hi   => abxcdexfg|hi   : fail: abxcdexfg|.hi expected. 
    ikegami 2: abxcdexfg.hi   => abxcdexfg|hi   : fail: abxcdexfg|.hi expected. 
     rindex: abxcdexfg.hi   => abxcdexfg|.hi  : ok