Search code examples
regexstringperl

Regex to search pattern surrounded by a common pattern repetitively


I have following string.

$str = "abafghababa";

I want to search pattern aba and its count.

Expected output for count is 3

I was trying with $count = () = $str =~ /aba/; But this is resulting as 2 which is correct. But i want to findout a way where it can result as 3.


Solution

  • Since you want to match aba that are overlapping you will need to use lookaheads which is zero width assertion.

    You can use this rgex:

    /(?=(aba))/g
    

    And get the group count.

    RegEx Demo