kailash19
kailash19

Reputation: 1821

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.

Upvotes: 4

Views: 6106

Answers (4)

AmbroseChapel
AmbroseChapel

Reputation: 12097

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

You can do it with substr().

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149973

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

Upvotes: 1

stema
stema

Reputation: 93026

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).

Upvotes: 3

Brian Roach
Brian Roach

Reputation: 76908

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

Output:

5

Upvotes: 11

Related Questions