2013-03-13 76 views
0

空白和元我有一個這樣的字符串:替換在Python

str1 = "/path/happy (dog)" 

爲了某種目的,我想它想:

str2 = "/path/happy\ \(dog\)" 

我試圖重新使用:

str1 = "happy (dog)" 
tuple_1 = ('\s+','(',')') 


for i in tuple_1: 

    match = re.search(r"("+i+")",str1) 

    if match: 
     str1 = re.sub(match.group(),"\\"+match.group(),str1) 

print str1 

但它給出了錯誤:

sre_constants.error: unbalanced parenthesis 

我知道我在這裏缺少的東西...

+0

你必須在正則表達式中繞過括號。 – 2013-03-13 14:06:13

+0

你是否使用了你的錯誤信息? http://stackoverflow.com/questions/10318248/unbalanced-parenthesis-python – 2013-03-13 14:08:48

回答

1

即使你申請由其他答案(逃逸元組的搜索字詞),這是有效的和重要的提到的變化,你仍然可以獲得一個

Traceback (most recent call last): 
    File "<pyshell#4>", line 6, in <module> 
    str1 = re.sub(match.group(),"\\"+match.group(),str1) 
error: unbalanced parenthesis 

但這次在不同的路線。所以當你使用regex's sub function時,第一個參數需要是一個有效的正則表達式。 match.group()可能是任何東西,並不一定是平衡的。這是正則表達式窒息的地方。所以,我們可以從match.group()escape it中取出字符串,所以我們正在搜索文字。從而改變線

str1 = re.sub(re.escape(match.group()),"\\"+match.group(),str1) 

在另一方面,我們可以只編譯模式一次,並記住它 所以

pattern = re.compile(r"("+i+")") 
str1 = re.sub(pattern,"\\"+match.group(),str1) 

最後的代碼是:

str1 = "/path/happy (dog)" 
tuple_1 = (r'\s+', r'\(', r'\)') 
for i in tuple_1: 
    pattern = re.compile(r"("+i+")") 

    match = pattern.search(str1) 

    if match: 
     str1 = re.sub(pattern,"\\"+match.group(),str1) 

STR1現在是'/path/happy\\ \\(dog\\)'

+0

謝謝薩姆。它工作完美。雖然輸出是 '/路徑/高興\\(狗\\)',我真正想要的。 – vipulb 2013-03-14 08:42:32

2

你需要逃避任何特殊字符,如一個括號:

tuple_1 = (r'\s+', r'\(', r'\)') 

,否則他們將被相應地解釋爲正則表達式字符。

2

當i「(」所得的正則表達式將是「(()」。兩個開括號和一個封閉,因此錯誤消息「不平衡括號」。

必須逃避tuple_1兩個括號:

tuple_1 = (r'\s+', r'\(', r'\)')