How to find the nth character or digit in a string using REGEX in Perl

I would like to find the nth occurrence of a digit or symbol using regex in perl.

For example: if the line:

$string = 'abdg2jj4jdh5jfj6' 

I need to match the number 5, which is the 3rd digit.

How can I do this with regex.

+4
source share
4 answers
 my $string = "abdg2jj4jdh5jfj6"; my @myArray = ($string =~ /(\d)/g); print "$myArray[2]\n"; 

Output:

5

+11
source

An alternative to Brian Roachs would be to respond to such a capture group

 $string =~ /^\D*\d\D*\d\D*(\d)/; print $1; 

means match the beginning of a line with 0 or more digits ( \D ), then the digit ( \D ), the same thing, and then the digit you want to have in brackets, so it will be saved in $1 .

But you need a longer regex, so I would prefer its solution (+1).

+3
source
 my $k = 2; # one less than N my ($digit) = $string =~ /(?:\d.*?){$k}(\d)/; 
+1
source

Can you say "you do not need a regular expression"?

You can do this with substr() .

0
source

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


All Articles