Multiply all numbers in a string

Update - Perl - 17


15 characters + 2 for -i and -p flags.

We can use the -i flag to input a file extension, but since we aren't reading any files, we can use it to get the number and it the variable $^I will get assigned to it.

Run with:

perl -e'print"This 1 is22a 3352sentence 50"' | perl -i3 -pe's/\d+/$&*$^I/ge'

Perl - 21

Updated as per @Dennis's comment.


Run with -p flag.

Example run:

perl -e'print"This 1 is22a 3352sentence 50\n3"' | perl -pe'$n=<>;s/\d+/$&*$n/ge'


$n=<>; read in the number

-p prints the output

s/\d+/$&*$n/ge Read the input with <> and search for one or more digits and replace them with the digits times the number. g is global, e is eval the replace potion of the s///. $& contains what was matched and it multiplied by the number, $n.

You can read more about s/// in perlop and more about Perl regexes in perlre.

Another solution:

@F.Hauri pointed out you can also use the s switch to assign the $n variable to 4. I'm not sure how many characters this counts as but I'll leave it here:

perl -spe 's/\d+/$&*$n/ge' -- -n=4 <<<'This 1 is22a 3352sentence 50'

JavaScript (ES6) - 48 44 chars

Thanks to @bebe for saving one character. Update: 8/Mar/16, removed another four characters



var sentence = prompt(),
    num = parseInt(prompt(), 10); // base 10

sentence = sentence.replace(/\d+/g, digit => digit * num);


43 chars:



Requires number input first and then sentence. Cut one char more here thanks @bebe again!

Python 2 (79)

import re
print re.sub('\d+',lambda x:`int(*n`,s)

Sample run

$ python
"This 1 is22a 3352sentence 50"
This 3 is66a 10056sentence 150

Online demo:


Code Golf