-1

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,

rshdzrt
  • 125
  • 7
  • 3
    Can you be more specific? What is the expected result for string `gfoobar9g9g`? – Hao Wu Dec 14 '21 at 06:35
  • 3
    I suspect that this question isn't a duplicate as marked but please edit the question to make it clearer – zdim Dec 14 '21 at 08:53
  • I am voting to reopen, and in this case I'd like to explain. The other page, which this is marked as a duplicate of, is a question about the regex itself, comparing its ways. This one is a generic programming question (even as it asks for regex) and It is not a given that _that_ particular regex technique yields the best answer (even as it probably does), Also, those answers do not directly, nor fully, answer this question, and applying them blindly may leave out some bits. Finally, I take into account that others already voted to reopen. – zdim Dec 16 '21 at 17:47
  • For reference and anyone's review, that other page, which this question was marked a duplicate of, is: [Using explicitly numbered repetition instead of question mark, star and plus](https://stackoverflow.com/questions/3032593/using-explicitly-numbered-repetition-instead-of-question-mark-star-and-plus) – zdim Dec 16 '21 at 17:51
  • Check out the Perl regex tutorial. https://perldoc.perl.org/perlretut – lordadmira Dec 17 '21 at 03:10

1 Answers1

1

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 ) ...
zdim
  • 64,580
  • 5
  • 52
  • 81