Une approche différente, vient de mettre une barre oblique avant []
que si elles aren 't suivi par x]
ou précédé de [x
.
result = re.sub(r"(\[(?!x\])|(?<!\[x)\])", r"\\\1", subject)
Explication:
# (\[(?!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 «\]»
Ah, .. où vous pouvez obtenir +4 pour "me donner la codez" ces jours-ci. – geoffspear
J'ai appris des réponses ci-dessous. C'est l'idée, non? Merci à tous ceux qui m'ont aidé. Choisir la réponse est difficile cependant. Je vais donner à la regex comme j'en ai appris plus. – saroele