Multiply by searching and replacing

Can regular expressions be used to do arithmetic? For example, find all the numbers in a file and multiply them by a scalar value.

+3
source share
6 answers

I prepared a small script that uses re.finditerto find all integers (you can change the regular expression so that it can deal with floats or scientific notation) and then use mapto return a list of scaled numbers.

import re

def scale(fact):
    """This function returns a lambda which will scale a number by a                           
    factor 'fact'"""
    return lambda val: fact * val

def find_and_scale(file, fact):
    """This function will find all the numbers (integers) in a file and                        
    return a list of all such numbers scaled by a factor 'fact'"""
    num = re.compile('(\d+)')
    scaling = scale(fact)
    f = open(file, 'r').read()
    numbers = [int(m.group(1)) for m in num.finditer(f)]
    return map(scaling, numbers)

if __name__ == "__main__":
    import sys
    if len(sys.argv) != 3:
        print "usage: %s file factor" % sys.argv[0]
        sys.exit(-1)
    numbers = find_and_scale(sys.argv[1], int(sys.argv[2]))
    for number in numbers:
        print "%d " % number

file, fact, script python script.py file fact, STDOUT . , - , ...

+2

, re.sub() :

import re

def repl(matchobj):
  i = int(matchobj.group(0))
  return str(i * 2)

print re.sub(r'\d+', repl, '1 a20 300c')

:

2 a40 600c

:

re.sub(pattern, repl, string [, ])

repl - , . .

+8

perl /e. . , $

 my $scalar= 4;
 $line =~ s/([\d]+)/$1*$scalar/ge;

. , $ , "foo2 bar25 baz", "foo8 bar100 baz"

+4

- , sed . - , python perl.

+1

, , sed , . .

+1

Ayman Hourieh , , imo :

>>> import re
>>> repl = lambda m: str(int(m.group(0)) * 2)
>>> print re.sub(r'\d+', repl, '1 a20 300c')
2 a40 600c
-1

Source: https://habr.com/ru/post/1742517/


All Articles