Question: 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!

Answer: 
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.
The following code does what you want on the string you gave as an example. One point is that it is very specific to the format of this one string. It can't manage any variability in the string. It is really limited to only this type of string format.

```
import re

ss = '''PART 1 DATA MODELS Chapter
2 Entity-Relationship Model 27

The sun is shining

PART 1 DATA MODELS Chapter
13 Entity-Relationship Model 45
'''

regx = re.compile('^(PART.*)(\n(\d*).*\s(\d+)\n)',re.MULTILINE)

def repl(mat):
    return ''.join((mat.group(1),' ',
                    str(int(mat.group(4))-int(mat.group(3))),
                    mat.group(2)))

for mat in regx.finditer(ss):
    print mat.groups()

print

print regx.sub(repl,ss)

```

result

```
('PART 1 DATA MODELS Chapter', '\n2 Entity-Relationship Model 27\n', '2', '27')
('PART 1 DATA MODELS Chapter', '\n13 Entity-Relationship Model 45\n', '13', '45')

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

The sun is shining

PART 1 DATA MODELS Chapter 32
13 Entity-Relationship Model 45

```

**Edited**: I had forgotten the re.MULTILINE flag