2015-04-03 78 views
3

如果逗號前面有某個正則表達式,我想使用逗號分隔符來拆分字符串。考慮一下我的字符串格式爲: 「(可能有逗號的東西一堆)FOO_REGEX,(可能有逗號的其他東西)FOO_REGEX,...」我想用逗號分割字符串,但僅限於如果他們前面有FOO_REGEX:[「(可能有逗號的東西)FOO_REGEX」,「(其他可能有逗號的東西)FOO_REGEX」,tc。]。基於條件的Python拆分字符串

舉一個具體的例子,考慮拆分以下字符串:

"hi, hello! $$asdf, I am foo, bar $$jkl, cool" 

分爲三個串名單:

["hi, hello! $$asdf", 
"I am foo, bar $$jkl", 
"cool"] 

有沒有簡單的方法在Python做到這一點?

回答

1

如果FOO_REGEX爲固定寬度,則可以使用正面後視。在這裏,你會得到後您的線路拆分 「$$ ASDF」

看到一個sample working program

import re  
str = 'hi, hello! $$asdf, I am foo, bar $$jkl, cool' 
splts = re.split('(?<=\$\$asdf), *', str) 
print splts 

輸出:

['hi, hello! $$asdf', 'I am foo, bar $$jkl, cool'] 
2

你可以使用re.findall代替re.split

>>> import re 
>>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool" 
>>> [j for i in re.findall(r'(.*?\$\$[^,]*),\s*|(.+)', s) for j in i if j] 
['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool'] 

OR

使用外部regex模塊,以支持可變長度回顧後因爲re將不支持可變長度向後斷言。

>>> import regex 
>>> s = "hi, hello! $$asdf, I am foo, bar $$jkl, cool" 
>>> regex.split(r'(?<=\$\$[^,]*),\s*', s) 
['hi, hello! $$asdf', 'I am foo, bar $$jkl', 'cool'] 
+1

希望這會很快添加。因爲你給的鏈接太棒了 – 2015-09-23 10:46:01