$_ = "sin(atan2(sin(1),cos(1))),atan2(1,1),cos(atan2(sin(2),cos(2)))\n"; (my $re=$_)=~s/((\()|(\))|.)/${[')','']}[!$3]\Q$1\E${['(','']}[!$2]/gs; $re= join'|',map{quotemeta}eval{/$re/}; die $@ if $@ =~ /unmatched/; print while s/(\w+\(($re)\))/$1/ee;