如何在Python中修改此字符串

时间:2012-08-16 21:30:42

标签: python regex string

我有一个字符串,我需要在每个'['或']'前面加一个'\',除非括号括起一个像这样的x:'[x]'。在其他情况下,括号将始终包含一个数字。

实施例: 'Foo[123].bar[x]'应该成为'Foo\[123\].bar[x]'

实现这一目标的最佳方法是什么?非常感谢。

3 个答案:

答案 0 :(得分:8)

这样的事情应该有效:

>>> import re
>>>
>>> re.sub(r'\[(\d+)\]', r'\[\1\]', 'Foo[123].bar[x]')
'Foo\\[123\\].bar[x]'

答案 1 :(得分:6)

你可以在不达到这样的正则表达式的情况下做到这一点:

s.replace('[', '\[').replace(']', '\]').replace('\[x\]', '[x]')

答案 2 :(得分:0)

一种不同的方法,只有在[]后面跟x][x前面时才在result = re.sub(r"(\[(?!x\])|(?<!\[x)\])", r"\\\1", subject) 之前加上斜杠。

# (\[(?!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 «\]»

<强>解释

{{1}}