I'm struggling to find a solution, I'm trying to make a simple app in Perspective that can take FactoryTrash ME window exports and do a search and replace. I have a lookup table that is the current address and what the new address should be.
Here is a short example:
import re
oldAddress = "::[PLC]N22:21"
newAddress = "[PLC]N22[21]"
data = '<connection name="Value" expression="{::[PLC]N22:211} * .1"/>'
data = data.replace(oldAddress, newAddress)
print data
Result:
<connection name="Value" expression="{[PLC]N22[21]1} * .1"/>
The issue is it should be:
<connection name="Value" expression="{[PLC]N22[21]} * .1"/>
When I want to match whole word boundaries I will use this:
data = re.sub(r"\b%s\b" % re.escape(oldAddress), newAddress, data)
However, this doesn't work with square brackets in the string.
How can I escape square brackets and still search with boundaries?
To have regex see square brackets, you have to escape them with \
.
However, help me understand. Your oldAddress ends with 21, not 211, so it would not replace the last 1 in the data string because its not part of the searched string. Don't you want your oldAddress to be ::[PLC]N22:211?
1 Like
I tried escaping with backslashes and I couldn't get it to work, but perhaps I was overlooking something.
In my example, nothing should have been replaced, {::[PLC]N22:211}
should have remained as-is. My point was using replace
would still replace the text, which is why I wanted to use boundaries.
I'll be honest, this app is really simple and it's just something I want to use for conversion projects. So, not important, IMO, to be best practice, so for right now I just added back in the curly brackets, then do the replace. I should have mentioned this is replacing direct tags which are always wrapped in curly brackets and will include a shortcut (the stuff with square brackets).
I found some of the online regex generators useful. e.g.
2 Likes
You can end your regex expression with (?=})
to specify that is should be followed by a curly brace but not included. This is a positive lookahead.
Not matching:
Matching:
1 Like