简体   繁体   中英

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

I would like to find nth occurence of a digit or character using regex in perl.

For example: If the string is:

$string = 'abdg2jj4jdh5jfj6'

i need to match the digit 5 which is the 3rd digit.

How can i do it with regex.

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

Output:

5

The alternative to Brian Roachs answer would be to use a capturing group like this

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

means match from the start of the string 0 or more non-digits ( \\D ) then a digit ( \\d ), the same again and then the digit you want to have in brackets, so it would be stored in $1 .

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

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

Am I allowed to say "you don't need a regex"?

You can do it with substr() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM