dimanche 3 juillet 2016

Regex avoid "rest of string" split results

I have this code to split a complicated CSV file into chunks. The hard bit is that commas may also appear within "" and thus those must not be split on. The regex I am using to find commas not within "" works fine: comma_re = re.compile(r',(?=([^"]*""[^"]*"")*[^"]*$)')

Demo: here

import re


test = 'Test1,Test2,"",Test3,Test4"",Test5'
comma_re = re.compile(r',(?=([^"]*""[^"]*"")*[^"]*$)')

print comma_re.split(test)

Output:

['Test1', 'Test2,"",Test3,Test4""', 'Test2', '"",Test3,Test4""', '"",Test3,Test4""', None, 'Test5']

Desired: ['Test1', 'Test2', '"",Test3,Test4""', 'Test5']

How can I avoid the useless split results?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire