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?
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 ]
In addition to vpekar answer, you can also use backreferences of your pattern on the replacement string, so you can try to match all between / or \ and recreate the string using your new number and backreferences:
line = '[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]'
re.sub(r'([\\|/].*\s)(?:17)(\s.*[\\|/])', r'\g<1>19\2', line)
which returns:
'[ 17 plane_17 \ 23 25 19 99 150 248 \ noname ]'
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