#This works $meth_impl =~ s/((? \w+($brackets)?( \s*(\.|->)(?&identifier))?)) \s* \. \s* Trim\(\)/Trim($1)/xg; #This doesn't match anything: $meth_impl =~ s/($identifier) \s* \. \s* Trim\(\)/Trim($1)/xg;