May-15-2023, 05:21 PM
Here is a way, using re.sub
from itertools import pairwise import re def our_split(data): level = 0 position = [-1] def _sub(match): nonlocal level c = match.group(0) level += {'[': 1, ']': -1}.get(c, 0) if c == ',' and not level: position.append(match.start()) re.sub(r'[\[\],]', _sub, data) position.append(len(data)) return [data[u+1:v] for u, v in pairwise(position)] if __name__ == '__main__': data = "Richtung route, trend, way [route, direction], tendency [political etc.], course [direction], direction [course, route]" result = our_split(data) print(result)
Output:['Richtung route', ' trend', ' way [route, direction]', ' tendency [political etc.]', ' course [direction]', ' direction [course, route]']