Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic operations in regex

Tags:

python

regex

I am using gedit regex plugin (Python style regex). I would like to do some arithmetic operation on a backreference to a group.

For example:

PART 1 DATA MODELS Chapter  
2 Entity-Relationship Model 27

I would like to change it to be

PART 1 DATA MODELS Chapter  25
2 Entity-Relationship Model 27

My regex is ^(PART.*)\n(.*\s(\d+))\n, and I would like to replace it with something like \1 (\3-2)\n\2\n where \3-2 is meant to be the backreference \3 minus 2. But the replacing regex is not right. I wonder how to do it? Thanks!

like image 990
Tim Avatar asked Jul 26 '11 02:07

Tim


1 Answers

You can pass to re.sub lambda function which takes re.MatchObject object for every non-overlapping pattern match and returns replacement string. For example:

import re    
print re.sub("(\d+)\+(\d+)",
             lambda m: str(int(m.group(1))+int(m.group(2))),
             "If 2+2 is 4 then 1+2+3+4 is 10")

prints

If 4 is 4 then 3+7 is 10

You could easily apply it to your problem.

like image 199
tomasz Avatar answered Oct 11 '22 20:10

tomasz