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: 
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
Unless gedit is a superset of Python, it won't allow operations inside a replace-regex as you're trying to do with `(\3-2)`. In any case, `\3` is a string and you'd need to convert with int() first.
So you'd have to break it into separate *re.search(...)*, compute the inserted pageno, then insert.

Second issue is that you did not match the pagelength of '2', you hardcoded it in =- did you want your regex to match it from the start of second line?

(Also in any case your multiline match will only match one line following the PART, if that's what you intended.)

Here it is implemented in plain Python regex:

```
for (chap,sect,page) in re.finditer(r'^(PART.*)\n(.*\s+(\d+))\n', input, re.M):
    print chap, int(page)-2
    print sect

```

(I tried to wrap that as a repl fn `paginate_chapter(matchobj)`, can't get re.sub to call that reliably yet...)