2015-04-07 90 views
3

這是我的輸入和結果的正則表達式:從提取的正則表達式的值刪除括號

temp2 = '(LEFT-WALL)(who)(is.v)(the)(di(rect)or.n)(of)(Inceptio)(RIGHT-WALL)' 
print regex.findall(r'\([^\)\(]*+(?:(?R)[^\)\(]*)*+\)', temp2) 

結果:

['(LEFT-WALL)', '(who)', '(is.v)', '(the)', '(di(rect)or.n)', '(of)', '(Inceptio)', '(RIGHT-WALL)'] 

我想這種結果的:;

['LEFT-WALL', 'who', 'is.v', 'the', 'di(rect)or.n', 'of', 'Inceptio', 'RIGHT-WALL'] 

正則表達式的任何變化?

回答

3

由於不使用正則表達式的替代,你可以做的工作只是str.split()str.strip()方法:

>>> [i.strip('()') for i in temp2.split(')(')] 
['LEFT-WALL', 'who', 'is.v', 'the', 'di(rect)or.n', 'of', 'Inceptio', 'RIGHT-WALL'] 

或用正則表達式,你可以在你的正則表達式使用look-around

>>> re.findall(r'(?<=\()(.*?)(?=\)\(|\)$)', temp2) 
['LEFT-WALL', 'who', 'is.v', 'the', 'di(rect)or.n', 'of', 'Inceptio', 'RIGHT-WALL'] 

邏輯很簡單,你只需要匹配左括號(和後面緊跟的開括號012 )(

1

您需要匹配()(之間或)()之間的字符串。這樣你可以避免在'(di(rect)or.n)'中匹配'(rect)'等字符串。你可以使用lookaround assertions來做到這一點,因爲它們不會消耗搜索到的字符串。

先行斷言:未來

(?=...) 匹配,如果匹配...,但不消耗任何的字符串。 這被稱爲超前斷言(lookahead assertion)。例如,Isaac (?=Asimov)只有跟在'Asimov'之後纔會匹配'Isaac '

正向後斷言

(?<=...) 匹配,如果字符串中的當前位置由匹配......這在當前位置結束之前。這稱爲 積極的lookbehind斷言。 (?<=abc)def會在 abcdef中找到一個匹配項,因爲後視會備份3個字符,並檢查包含的模式是否匹配 。

在下面的代碼中,我使用re.VERBOSE標誌使其更具可讀性。

pattern = re.compile(r""" 

(?<= \() .+? (?= \)\() # Matches string after a '(' and before a ')(' 

|         # or... 

(?<= \)\() .+? (?= \) ) # Matches string after a ')(' and before a ')'  

""", re.VERBOSE) 


print (re.findall(pattern, temp2)) 
1

我覺得你並不需要對樣品字符串的任何正則表達式您提供:在sample program

temp2 = '(LEFT-WALL)(who)(is.v)(the)(di(rect)or.n)(of)(Inceptio)(RIGHT-WALL)' 
if temp2[0:1] == "(" and temp2[-1:] == ")": 
    print temp2[1:-1].split(")(") 

輸出:

['LEFT-WALL', 'who', 'is.v', 'the', 'di(rect)or.n', 'of', 'Inceptio', 'RIGHT-WALL']