2016-10-13 73 views
0

比方說,我有這樣的文字:拆分並保持deliminator,最好用正則表達式

1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third 

,我想:

["1.1 This is the 2,1 first","1.2 This is the 2,2 second","1.3 This is the 2,3 third"] 

需要注意的是:

  • 我不能使用re.findall,因爲我無法想出一種方法來正確終止比賽。我能想到的最好的是'[0-9]+\.[0-9]+^([0-9]+\.[0-9]+)*',這是行不通的。

  • 我不能將分隔符存儲爲全局變量,因爲它隨每個匹配而變化。

  • 我無法使用常規的re.split,因爲我想保留分隔符。我不能使用逆序,因爲它必須是固定的寬度,而事實並非如此。

我已閱讀regexp split and keep the seperatorPython split() without removing the delimiterIn Python, how do I split a string and keep the separators?,仍然沒有答案。

+0

但你*不*一定要小心你分裂的分隔符(空格)。 – jonrsharpe

回答

2

是的,你可以:

\b\d+\.\d+ 
.+?(?=\d+\.\d+|$) 

看到它working on regex101.com。至除了用於re.findall()

import re 
rx = re.compile(r'\b\d+\.\d+.+?(?=\d+\.\d+|$)') 
string = "1.1 This is the 2,1 first 1.2 This is the 2,2 second 1.3 This is the 2,3 third " 
matches = rx.findall(string) 
print(matches) 
# ['1.1 This is the 2,1 first ', '1.2 This is the 2,2 second ', '1.3 This is the 2,3 third '] 

如果字符串跨越多行的,使用DOTALL模式[\s\S]*?
請參閱a demo on ideone.com

0

分裂空白,其右側是1.2 2.2 ...

re.split(r' (?=\d.\d)',s)