Search code examples
julia

Substitute number by their double in string


I am struggling in substituting numbers by their doubles in a string. How can I achieve that?

None of these work for me (I am on Julia v1.8):

replace("hello num12 text and num5 numbers",r"num([0-9]+)"=>2*s"\1")
replace("hello num12 text and num5 numbers",r"num([0-9]+)"=>2*parse(Int,s"\1"))
replace("hello num12 text and num5 numbers",r"num([0-9]+)"=>2*parse(Int,SubstitutionString("\\1")))

Input:

"hello num12 text and num5 numbers"

Expected output (delete string "num" and replace the number by its double):

"hello 24 text and 10 numbers"

Any help will be greatly appreciated.

Edit: typos.


Solution

  • For your case you need to pass a function as a second argument:

    julia> replace("hello num12 text and num5 numbers",r"num([0-9]+)" => x -> 2*parse(Int, chop(x, head=3, tail=0)))
    "hello 24 text and 10 numbers"