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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With