2012-08-16 22 views
1

我有一個字符串,我需要在每個'['或']'前添加一個'\',除非括號括起來像這樣:'[x] 」。在其他情況下,方括號總是包含一個數字。如何在Python中修改此字符串

例如: 'Foo[123].bar[x]'應該變成'Foo\[123\].bar[x]'

達到此目的的最佳方法是什麼?預先感謝了很多。

+2

啊,所以..在這裏你可以得到+4 「給我codez」 這些天。 – geoffspear 2012-08-16 23:11:04

+0

我從下面的答案中學到了。這是主意,對吧?感謝所有幫助我的人。但挑選答案很困難。當我從中學到更多東西時,我會把它給予正則表達式。 – saroele 2012-08-17 08:08:03

回答

8

像這樣的東西應該工作:

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

這是一個很好的解決方案(只需預先編譯正則表達式)。它可能會發生,它比三個鏈替換稍慢,因爲正則表達式引擎意味着一些開銷。但無論如何,這個解決方案更容易理解,並且如果未來需求發生變化,將更容易修改。 – dsign 2012-08-16 21:42:34

+0

我是一個正則表達式的新手,但從網絡的一點幫助,我可以找出爲什麼這也適用。謝謝,值得多學習一下我看到的正則表達式。 – saroele 2012-08-16 22:03:09

+0

@saroele我建議[本教程](http://code.google.com/edu/languages/google-python-class/regular-expressions.html)。 – 2012-08-16 22:13:13

6

你可以做到這一點沒有達到像這樣regexs:

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

結果字符串的三次完整掃描以實現所需的輸出?對於長字符串,這將表現不佳。 – 2012-08-16 21:34:40

+4

當然,在這種情況下,我會主張正則表達式的方法。我提出(可以說)一個概念上更簡單的方法,當這不是一個問題時。如果性能問題,單線性掃描(只有一個超前)將勝過正則表達式。 – cmh 2012-08-16 21:37:08

+2

在測試字符串''Foo [123] .bar [x] zzzzz'* 100000',長度爲2M字符時,我發現're.sub'需要250 ms(即使確保該模式已編譯),而替換'只需要36毫秒。 – DSM 2012-08-16 21:44:05

0

不同的方法,只是把一個斜線[]之前,只有當他們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 «\]»