s/(\G # Either were we finished the previous time # (or at the beginning the first time). | # Or (.)(?!\2)) # A character ($2) not followed by itself ( # Capture ($3) (.)\4(?!\4) # A character ($4) followed exactly once by itself. ) # End capture ($3) /$2($3)/xg # Replace with $2 (what preceeded) followed by # "($3)" (the duplicate).