$str = 'blfoo and barthisfoothatqux and barsofooquxhim andfoosom foo'; $str =~ s[(bar.+?qux)|(foo)][defined $2 ? '123' : $1]ge; print $str; bl123 and barthisfoothatqux and barsofooquxhim and123som 123