Reputation: 61
I'm trying to find the index of the first occurrence of a number from 0-9.
Let's say that:
$myString = "ABDFSASF9fjdkasljfdkl1"
I want to find the position where 9 is.
I've tried this:
print index($myString,[0-9]);
And:
print index($myString,\d);
Upvotes: 6
Views: 1732
Reputation: 3535
You can try this:
perl -e '$string="ABDFSASF9fjdkasljfdkl1";@array=split(//,$string);for $i (0..$#array) {if($array[$i]=~/\d/){print $i;last;}}'
Upvotes: 0
Reputation: 902
You can try even below perl code:
use strict;
use warnings;
my $String = "ABDFSASF9fjdkasljfdkl11";
if($String =~ /(\d)/)
{
print "Prematch string of first number $1 is $`\n";
print "Index of first number $1 is " . length($`);
}
Upvotes: 0
Reputation: 35208
Use regex Positional Information:
use strict;
use warnings;
my $myString = "ABDFSASF9fjdkasljfdkl1";
if ($myString =~ /\d/) {
print $-[0];
}
Outputs:
8
Upvotes: 9