Perl 从字符串中提取子字符串
我还是个笨蛋。我得到一个字符串,可以是man_1,man_2,woman1,woman2等。。(没有逗号,并且只有一个字符串作为函数的输入) 我需要检查if语句中的man_uu或woman作为子字符串,以确保提取了适当的数字并添加了一些偏移量 我可以提取的数字如下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
$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";
}
在您的示例中,存在两个问题:
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,就像一个符咒。谢谢