1

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

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

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

4

3 回答 3

8

像这样的东西应该可以工作:

>>> import re
>>>
>>> re.sub(r'\[(\d+)\]', r'\[\1\]', 'Foo[123].bar[x]')
'Foo\\[123\\].bar[x]'
于 2012-08-16T21:33:40.263 回答
6

你可以做到这一点,而无需使用这样的正则表达式:

s.replace('[', '\[').replace(']', '\]').replace('\[x\]', '[x]')
于 2012-08-16T21:33:57.793 回答
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 «\]»
于 2012-08-16T21:38:09.353 回答