从字符串中提取子字符串

时间:2013-02-06 19:32:55

标签: perl substring extract

我仍然是一个perl noob。我得到一个字符串,可以是man_1,m​​an_2,woman1,woman2等。(没有逗号,只有一个字符串作为函数的输入)。

我需要在if语句中检查man_或woman作为子字符串,以确保提取适当的数字并添加一些偏移量。

我可以提取的数字如下

$num =~ s/\D//g
if (<need the substring extracted> == "man_")
    $offset = 100;
else if (<need the substring extracted> == "woman")
    $offset = 10;

return $num + $offset;

现在我如何提取子字符串。我查看了substr,它需要抵消,什么不是。无法弄清楚。感谢帮助

3 个答案:

答案 0 :(得分:0)

解决方案:

if ( $num =~ m{^man_(\d+)$} ) {
    return 100 + $1;
} elsif ( $num =~ m{^woman(\d+)$} ) {
    return 10 + $1;
} else {
    die "Bad input: $num\n";
}

在您的示例中,存在几个问题:

  1. s / \ D // g - 将逐个删除字符,而不是所有\ D字符的大块。所以没有变量可以是“man _”
  2. 从regexp获取数据,你应该使用分组parens,比如s /(\ D)//
  3. 要获取所有字符,您应该使用*或+运算符,例如:s /(\ D +)//
  4. 无需修改即可更好地匹配,因为它可以更好地处理格式错误数据的边缘情况。

答案 1 :(得分:0)

depesz有一个很好的解决方案。这是另一个:

my %offsets = (
   'man_'  => 100,
   'woman' =>  10,
);

my ($prefix, $num) = $str =~ /^(\D+)(\d+)\z/
   or die;
my $offset = $offsets{$prefix}
   or die;
return $num + $offset;

答案 2 :(得分:0)

另一种选择:

return $2 + ( $1 eq 'man_' ? 100 : 10 )
  if $num =~ /^(man_|woman)(\d+)\z/;

die;