字符串匹配和提取

时间:2011-04-14 18:09:18

标签: regex perl string-split

我有一个像“ab.cde.fg.hi”这样的字符串,我想把它分成两个字符串。

  1. “ab.cde.fg”
  2. “喜”
  3. 怎么做?我写了一些代码,它会让我得到第二个字符串但是如何检索剩下的?

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

4 个答案:

答案 0 :(得分:1)

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

您还可以使用split

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

答案 1 :(得分:1)

你确定你不是在寻找......

($name,$path,$suffix) = File::Basename::fileparse($fullname,@suffixlist);

答案 2 :(得分: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;

答案 3 :(得分:0)

宣传我的想法使用rindex获取

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

来自"ab.cde.fg.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