$s = 'bbaaccbab sdbcbalsbadcbnw';; ## with added bs ($t = $s) =~ s[(b)(?=a[^\s]+$)][B]g; print $t;; bbaaccbab sdbcBalsBadcbnw