gilthoniel has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm trying to write a script that will return the substring of a string that starts and ends with specific characters ex: string: asdfgfhjkl parameters: start with f and end with j return: fgfhj, fhj I've tried regex but it will only return the full string if it contains an f followed by a j at some point. Thanks
  • Comment on Return string that starts and ends with specific characters

Replies are listed 'Best First'.
Re: Return string that starts and ends with specific characters
by Anonymous Monk on Jun 02, 2016 at 16:46 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1164776 use strict; use warnings; my @answer; 'asdfgfhjkl' =~ /f.*j(?{push @answer, $&})^/; print "$_\n" for @answer;
      I had basically the same idea, but tried \0 to force the backtracking. (which didn't work)

      Why and how does ^ work?

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

        It works with (?=\0) so I'd say it comes from zero-width assertions preventing optimization.

        Edit : In this special case (single word without a j at the end) it also works with \b

        I think regex is smart enough to detect no \0 but not ^

Re: Return string that starts and ends with specific characters
by Anonymous Monk on Jun 02, 2016 at 16:49 UTC
    #!/usr/bin/perl # http://perlmonks.org/?node_id=1164776 use strict; use warnings; print "$1\n" while 'asdfgfhjkl' =~ /(?=(f.*j))/g

      The previous one works not only with multiple 'f's but also with multiple 'j's, this one will always match up to the rightmost 'j'.

        Yep. I was not sure what his actual requirements were, so I showed both.

        Thanks this is great! How would I get it to print only to the leftmost j?