MaxCarp has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I want to insert some set of characters as a prefix (or suffix) to all occurrences of a certain substring.

For example, if I have xxx12xxxx345xxxxx6789xxxx

(where x is some non-digit character), and I want to insert the word 'found' before each string of digits to give

xxxfound12xxxxfound345xxxxfound6789xxxx

Using

s/[0-9]*/found/g

will (obviously) just insert found to replace all of the digits. How do I modify the regular expression to keep the digit substring and insert the found, along the lines of

s/[0-9'*/found[something]/g

Thank you, Max

Replies are listed 'Best First'.
Re: inserting string using regular expression
by toolic (Bishop) on Aug 16, 2011 at 16:57 UTC
    Use capturing parens (see perlre):
    use warnings; use strict; my $s = 'xxx12xxxx345xxxxx6789xxxx'; $s =~ s/([0-9]+)/found$1/g; print "$s\n"; __END__ xxxfound12xxxxfound345xxxxxfound6789xxxx
    Note the use of + (1 or more matches) instead of * (0 or more).
Re: inserting string using regular expression
by jwkrahn (Abbot) on Aug 16, 2011 at 16:56 UTC
    $ perl -le'$_ = q/xxx12xxxx345xxxxx6789xxxx/; print; s/(?=\d+)/found/g +; print' xxx12xxxx345xxxxx6789xxxx xxxfound12xxxxfound345xxxxxfound6789xxxx