Multiply all numbers in a string

Update - Perl - 17

s/\d+/$&*$^I/ge

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.

$n=<>;s/\d+/$&*$n/ge

Run with -p flag.

Example run:

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

Explanation:

$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

b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b))

Ungolfed:

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

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

alert(sentence);

43 chars:

(p=prompt)(p(b=p()).replace(/\d+/g,y=>y*b))

b=(p=prompt)();p(p().replace(/\d+/g,y=>y*b))

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


Python 2 (79)

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

Sample run

Input:
$ python mult.py
3
"This 1 is22a 3352sentence 50"
Output:
This 3 is66a 10056sentence 150

Online demo: http://ideone.com/V6jpyQ

Tags:

Code Golf