fiacobelli
fiacobelli

Reputation: 1990

Replace all occurrences of a regexp group after processing the string in the group

I have a string like this one:

text = '''this \sum 1,2 \end is three and \sum 2,3,4 \end is nine'''

and I have a function that adds numbers in a string

def add(numbers):
    return sum(map(lambda x:int(x), numbers.split(",")))

How can I, using regexps, replace all instances of '\\sum (.+?) \\end' by passing the group through the add function? i.e. the string above should be:

'''this 3 is three and 9 is nine'''

I can get the "1,2" and "2,3,4" using findall and add them, but how do I insert them back in the text where they are supposed to go? perhaps a combination of findall and split? is there a more straightforward way to do this in python?

Upvotes: 2

Views: 293

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Instead of re.findall(), use re.sub() and use a function to process each group.

The return value of the function is used as the replacement string:

re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)

The lambda creates a function that accepts one argument, the match object. It returns a string based on the number group, passed through add().

Demo:

>>> import re
>>> text = '''this \sum 1,2 \end is three and \sum 2,3,4 \end is nine'''
>>> def add(numbers):
...     return sum(map(lambda x:int(x), numbers.split(",")))
... 
>>> re.sub(r'\\sum ([\d,]+) \\end', lambda m: str(add(m.group(1))), text)
'this 3 is three and 9 is nine'

Upvotes: 2

Related Questions