$string =~ s/ //gs; # remove spaces $string =~ s/\((\w+)\*(\d+)\)\+\(\1\*(\d+))/($1\*(?{$2+$3})\)/gsx;