Home > Enterprise >  How to match character/letter/symbol/digit at nth index in a string using regex in Perl
How to match character/letter/symbol/digit at nth index in a string using regex in Perl

Time:12-17

I was trying to match a character/letter/symbol/digit of a string at nth index using regex.

my string is a server name and can be a 10 - 11 character string like this.

$string = gfoobar9gac i.e after 9g it can be any thing it can be a 10 characters or 11

I tried below options

   if ("$string" =~ m/\w[8]g/i){
      print "worked.\n";
   } else {
      print "Not worked\n";
   } 

m/\w[8]g/i - Doesn't work
m/g*.1g.*/i - works but if the string contains another 9g (gfoobar9g9g)it doesn't work and more specifically I only need the g at the index 8
/9g/ - This one fails too as there might 2 9g's in the string.

can someone please suggest something else using regex only.

Thanks,

CodePudding user response:

Syntax for specifying the number of matching repetitions is with {}

So to check whether g is the 9-th character in a $string

$string =~ /^\w{8}g/

This assumes a restriction that g is preceded by "word"-characters, matched by \w. To match any character use the pattern .. The anchor is needed since without it you'd check merely whether g is preceded by 8 word-characters, wherever it may be in the string.

In order to capture an unknown 9-th character

my ($char) = $string =~ /^\w{8}(.)/;

The parens in ($char) are needed to impose a list context on the match operator so that it returns the actual matches (one in this case), not only true/false.

Then to check whether $char is at the $n-th position in a $string

$n_prev_chars = $n - 1;

if ( /$string =~ /^\w{$n_prev_chars}$char/ ) ...

I don't know why that restriction to regex only but let me state a basic substr-based way as well

if ( substr($string, $n, 1) eq $char ) ...
  • Related