Home > Back-end >  operation on all numbers iwthin a text
operation on all numbers iwthin a text

Time:09-29

I would like to multiply all numbers within a text file by the same factor. I don't really know where to begin with (I am currently trying the re replace method but that doesn't seem to do the trick). Please help!

CodePudding user response:

With this:

Regex regex = new Regex(@"^\d$"); you get all the numbers.

So just multiply then.

(If you want to put them back to the text just get the index of these numbers).

CodePudding user response:

Use a regexp that matches numbers, and a function replacement. The function should parse the matched string as a number, multiply it by 2, then return that as a string.

import re

def int_or_float(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

text = "Blah blah 3 foo bar -15 xxx 124.3"
newtext = re.sub(r'-?\d (?:\.\d )?', lambda m: str(int_or_float(m.group(0)) * 2), text)
print(newtext)
# Output: Blah blah 6 foo bar -30 xxx 248.6
  • Related