Jonathan
Jonathan

Reputation: 83

Update numbers in the middle of a string

I'm looking at diff-style output, but I need to update the line numbers. So I see:

*** 1,2 *****
Actual line 1
Actual line 2
--- 1,2 -----
Expected line 1
Expected line 2

and in my results file, I'm at resline. So if resline=line 90, I'd want to change the second "1,2" to "91,92".

In perl, I'd use the following on the line that begins "---"

s/(\d+?)/($1+$resline)/eg

How should I do this in python?

Upvotes: 2

Views: 100

Answers (1)

Mu Mind
Mu Mind

Reputation: 11214

You would use re.sub and pass in a callable instead of a string as the replacement:

import re
re.sub(r'\d+?', lambda m: str(int(m.group(0))+resline), YOUR_STR)

Upvotes: 3

Related Questions