Perl 从字符串中提取子字符串

Perl 从字符串中提取子字符串,perl,substring,extract,Perl,Substring,Extract,我还是个笨蛋。我得到一个字符串,可以是man_1,man_2,woman1,woman2等。。(没有逗号,并且只有一个字符串作为函数的输入) 我需要检查if语句中的man_uu或woman作为子字符串,以确保提取了适当的数字并添加了一些偏移量 我可以提取的数字如下 $num =~ s/\D//g if (<need the substring extracted> == "man_") $offset = 100; else if (<need the substrin

我还是个笨蛋。我得到一个字符串,可以是man_1,man_2,woman1,woman2等。。(没有逗号,并且只有一个字符串作为函数的输入)

我需要检查if语句中的man_uu或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;
$num=~s/\D//g
如果(=“人”)
$offset=100;
否则,如果(=“女性”)
$offset=10;
返回$num+$offset;
现在如何提取子字符串。我看了substr,它需要偏移量什么的。我想不出来。感谢您的帮助

解决方案:

if ( $num =~ m{^man_(\d+)$} ) {
    return 100 + $1;
} elsif ( $num =~ m{^woman(\d+)$} ) {
    return 10 + $1;
} else {
    die "Bad input: $num\n";
}
在您的示例中,存在两个问题:

  • s/\D//g-将逐个删除这些字符,而不是像所有\D字符那样大的块。因此,没有一个变量是“man_”
  • 要从regexp获取数据,应该使用分组参数,如s/(\D)//
  • 要获取所有字符,应使用*或+运算符,如:s/(\D+)//
  • 在不修改的情况下进行匹配更好,因为它可以更好地处理格式错误数据的边缘情况

  • 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;
    
    另一种选择:

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

    对于传递给函数的字符串,数字可以一直到1024,就像一个符咒。谢谢