use strict; while () { s/[\s\(\)]+//g; # strip optional chars my @matches = m/(\d+)|([^\d]+)/g; print join ":", grep { defined $_ and $_ !~ m/^(r|rd|red)$/i } @matches; }