$text =~ s/^(|.*\s)(\d+)(\s.*|)$/$1$2<\/number>$3/ # The expression looks like the following # beginning of line followed by either nothing or at least # one space which neighbors a set of digits followed by # # either nothing or at least a space and the end of the line