从字符串中提取子串
问题描述:
我仍然是perl noob。我得到一个字符串,可以是man_1,man_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,它需要偏移量,而不是。无法弄清楚。感谢帮助
答
解决方案:
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_”
- 要从正则表达式中获取数据,您应该使用分组parens,如s /(\ D)//
- 要获取所有字符,应该使用*或+运算符,如:s /(\ D +)//
- 它更好地匹配而不修改,因为它可以更好地处理畸形数据的边缘情况。
+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;
答
另一种选择:
return $2 + ($1 eq 'man_' ? 100 : 10)
if $num =~ /^(man_|woman)(\d+)\z/;
die;
的数字可以一路到1024的字符串传递给工作就像一个魅力的功能 –