2016-04-12 34 views
2

我有例如蟒正則表達式分割上重複字符

-------------------------------- 
hello world ! 
-------------------------------- 
world hello ! 
-------------------------------- 
! hello world 

字符串和我希望能夠分裂的連字符的線條,連字符可以是可變長度這是爲什麼我決定用的正則表達式,我想要提取出來的信息是['hello world !', 'world hello !', '! hello world']我已經嘗試使用靜態數字連字符分割字符串,但這個工作但不確定如果它是可變長度的如何去處理它。我曾嘗試這樣做:

re.split(r'\-{3,}', str1) 

但似乎並沒有工作

+1

它是如何失效的?請參閱[本演示](https://regex101.com/r/eH8gU5/1) –

+1

'[x for x in(x.strip()for x in re.split(r' - {3,}',str1 ))if x]' – falsetru

+1

或者'[line for line in s.splitlines()if not re.match(' - +',line)]' – Maroun

回答

2

您可以剝去輸入不必要的空格,並導致分裂塊具有.strip()方法:

import re 
p = re.compile(r'(?m)^-{3,}$') 
t = "--------------------------------\nhello world !\n--------------------------------\nworld hello !\n--------------------------------\n! hello world" 
result = [x.strip() for x in p.split(t.strip("-\n\r"))] 
print(result) 

至於正則表達式,我建議限制在只有連字符的(?m)^-{3,}$匹配在行首(^)和行尾()之間的3個或更多連字符)(由於(?m),這些錨匹配線邊界,而不是字符串邊界)。

查看IDEONE demo