I'm working on a problem in Python in which I need to search and replace for a certain character everywhere in a string except when it is located between curly braces. I know how to do this when the character is between the braces, but not when is it located outside the braces. Essentially, I want the search to skip over anything between two delimiters.
My current work around is to perform a search and replace on the entire string, then again search and replace between braces to undo that portion of the last replace.
Here is an example of the functionality I'm looking for:
import re
>>> str = 'I have a _cat, here is a pic {cat_pic}. Another_pic {cat_figure}'
>>> re.sub(regex1,'/_',str)
'I have a /_cat, here is a pic {cat_pic}. Another/_pic {cat_figure}'
The current solution I am using is a two-step process as follows:
import re
>>> str = 'I have a _cat, here is a pic {cat_pic}. Another_pic {cat_figure}'
>>> s1 = re.sub('_','/_',str)
>>> s1
'I have a /_cat, here is a pic {cat/_pic}. Another/_pic {cat/_figure}'
>>> s2 = re.sub(r'\{(.+?)/_(.+?)\}', r'{\1_\2}', s1)
>>> s2
'I have a /_cat, here is a pic {cat_pic}. Another/_pic {cat_figure}'
Is there a way using regex to do this is one statement, or is the current two-step process the cleanest method?
Thanks