s/(.)\K( (?!\1).*)( \1.)/$3$2/s?redo:print for join$/,AA..ZZ