Reputation: 10099
I have a string in which I need to add a '\' in front of every '[' or ']', except if the brackets enclose an x like this: '[x]'. In the other cases, the brackets will always enclose a number.
Example:
'Foo[123].bar[x]'
should become 'Foo\[123\].bar[x]'
.
What is the best way to achieve this? Thanks a lot on beforehand.
Upvotes: 1
Views: 161
Reputation: 26930
A different approach, just put a slash before []
only if they aren't followed by x]
or preceded by [x
.
result = re.sub(r"(\[(?!x\])|(?<!\[x)\])", r"\\\1", subject)
Explanation:
# (\[(?!x\])|(?<!\[x)\])
#
# Match the regular expression below and capture its match into backreference number 1 «(\[(?!x\])|(?<!\[x)\])»
# Match either the regular expression below (attempting the next alternative only if this one fails) «\[(?!x\])»
# Match the character “[” literally «\[»
# Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!x\])»
# Match the character “x” literally «x»
# Match the character “]” literally «\]»
# Or match regular expression number 2 below (the entire group fails if this one fails to match) «(?<!\[x)\]»
# Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind) «(?<!\[x)»
# Match the character “[” literally «\[»
# Match the character “x” literally «x»
# Match the character “]” literally «\]»
Upvotes: 0
Reputation: 10927
You can do it without reaching for regexs like this:
s.replace('[', '\[').replace(']', '\]').replace('\[x\]', '[x]')
Upvotes: 6
Reputation: 47978
Something like this ought to work:
>>> import re
>>>
>>> re.sub(r'\[(\d+)\]', r'\[\1\]', 'Foo[123].bar[x]')
'Foo\\[123\\].bar[x]'
Upvotes: 8