in reply to Re^4: Why my Regex doesn't work
in thread Why my Regex doesn't work

yes just curiosity. I only recently started learning perl. Before I posted this question I didn't even knew lookarounds existed. Now I did a bit of reading about them and cool. If I knew about them I would have probably solved this myself. So I'm just curious if one does not know about lookarounds is this problem solvable. It would probably be very convoluted as I'm starting to think that regex is not always best for stirng matching and changing?

Replies are listed 'Best First'.
Re^6: Why my Regex doesn't work
by Anonymous Monk on Apr 11, 2017 at 21:44 UTC
    You can't do it in one pass without zero-width assertions of some kind, because the matches can't overlap. For instance,
    'ABABABA' =~ /ABA/g; # only matches twice #^^^ ^^^ here and here # ^^^ not here
    But I don't see any other zero-width assertions (besides lookarounds) that look like they would be helpful here. You can diddle with the match position outside of the regex engine to make it find overlapping matches. This matches three times:
    $_ = 'ABABABA'; while (/ABA/g) { print pos($_), "\n"; pos($_)--; }
    You're right, though, regexes aren't the solution for every problem. In particular, highly structured text (like HTML or program source code) can be difficult to manipulate with regexes alone.
      Generally, you'd need
      pos($_) -= length($&) - 1;

      instead of subtracting 1, because the overlap could be longer. Tested with

      $_ = "AAAABAAAA"; while (/AAA/g) { ...
      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,