Return values for string matching
Pretend I have a code in awk:
str_1 = "abc123defg";
m开发者_C百科atch(str_1, /[0-9]+/);
num_1 = substr(str_1, RSTART, RLENGTH);
Then num_1 will be "123". What is the Perl version of the same task?
Thanks in advance.
I'd translate that to:
my $num_1 = ($str_1 =~ /(\d+)/)[0];
I would usually do something like
my ($num_1) = $str_1 =~ /(\d+)/;
or
my $num_1;
if ($str_1 =~ /(\d+)/) {
$num_1 = $1;
}
In Perl's patterns \d
is equivalent to [0-9]
for ASCII strings.
It could be:
$str="abc123defg";
$str =~ /[0-9]+/;
$num_1 = $&;
Your awk translates directly into:
$str="abc123defg";
$str =~ /[0-9]+/;
$num_1 = substr($str, $-[0], $+[0]-$-[0]);
Which could be written as:
use English;
$str="abc123defg";
$str =~ /[0-9]+/;
$num_1 = substr($str, $LAST_MATCH_START[0], $LAST_MATCH_END[0]-$LAST_MATCH_START[0]);
精彩评论