Trying to find the index of the first number in a string using perl

I am trying to find the index of the first occurrence of a number from 0-9.

Say that:

$myString = "ABDFSASF9fjdkasljfdkl1" 

I want to find the position where 9 is.

I tried this:

 print index($myString,[0-9]); 

and

 print index($myString,\d); 
+6
source share
3 answers

Use regex Position Information :

 use strict; use warnings; my $myString = "ABDFSASF9fjdkasljfdkl1"; if ($myString =~ /\d/) { print $-[0]; } 

Outputs:

 8 
+9
source

You can try even below the 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($`); } 
0
source

You can try the following:

 perl -e '$string="ABDFSASF9fjdkasljfdkl1";@array=split(//,$string);for $i (0..$#array) {if($array[$i]=~/\d/){print $i;last;}}' 
0
source

Source: https://habr.com/ru/post/977601/


All Articles