regex/python to find and replace specific number within string

parsing, python, python-2.7, regex

Solution

You can use a callback function inside the sub part of the regex:

import re

def callback(match):
    return match.group(0).replace('17', '19')

s = "[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]"

s = re.compile(r'\\.+?\\').sub(callback, s)

print s

Prints:

[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]

Problem

I need to replace numbers (corners) that occur within a longer string that all look similar to this: ``` [ 17 plane_17 \ 23 25 17 99 150 248 \ noname ] ``` My function takes an "old" number to be replaced with a "new" number, and e.g. if that old number is 17 and the new is 19, then the outcome should be: ``` [ 17 plane_17 \ 23 25 19 99 150 248 \ noname ] ``` Note that only the numbers within \ \ should be replaced (these could also be / / ). To do this I tried to set up a regex substitution with the intention of avoiding numbers outside of \ \ or / /: `newplane = re.compile(r"[^[_] (" + str(oldcorner) + ")").sub(str(newcorner), oldplane)` I quickly realised that this doesn't work since regex searches from the start of the line and then fails if it doesn't match the pattern. There must be some clever way of doing it still that I don't know about.. Any suggestions?

Original source