我有一個字符串,我需要在每個'['或']'前添加一個'\',除非括號括起來像這樣:'[x] 」。在其他情況下,方括號總是包含一個數字。如何在Python中修改此字符串
例如: 'Foo[123].bar[x]'
應該變成'Foo\[123\].bar[x]'
。
達到此目的的最佳方法是什麼?預先感謝了很多。
我有一個字符串,我需要在每個'['或']'前添加一個'\',除非括號括起來像這樣:'[x] 」。在其他情況下,方括號總是包含一個數字。如何在Python中修改此字符串
例如: 'Foo[123].bar[x]'
應該變成'Foo\[123\].bar[x]'
。
達到此目的的最佳方法是什麼?預先感謝了很多。
像這樣的東西應該工作:
>>> import re
>>>
>>> re.sub(r'\[(\d+)\]', r'\[\1\]', 'Foo[123].bar[x]')
'Foo\\[123\\].bar[x]'
這是一個很好的解決方案(只需預先編譯正則表達式)。它可能會發生,它比三個鏈替換稍慢,因爲正則表達式引擎意味着一些開銷。但無論如何,這個解決方案更容易理解,並且如果未來需求發生變化,將更容易修改。 – dsign 2012-08-16 21:42:34
我是一個正則表達式的新手,但從網絡的一點幫助,我可以找出爲什麼這也適用。謝謝,值得多學習一下我看到的正則表達式。 – saroele 2012-08-16 22:03:09
@saroele我建議[本教程](http://code.google.com/edu/languages/google-python-class/regular-expressions.html)。 – 2012-08-16 22:13:13
你可以做到這一點沒有達到像這樣regexs:
s.replace('[', '\[').replace(']', '\]').replace('\[x\]', '[x]')
不同的方法,只是把一個斜線[]
之前,只有當他們AREN之後是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 «\]»
啊,所以..在這裏你可以得到+4 「給我codez」 這些天。 – geoffspear 2012-08-16 23:11:04
我從下面的答案中學到了。這是主意,對吧?感謝所有幫助我的人。但挑選答案很困難。當我從中學到更多東西時,我會把它給予正則表達式。 – saroele 2012-08-17 08:08:03