Warm tip: This article is reproduced from serverfault.com, please click

Python function which split string by ',' and ignore ':'

发布于 2020-11-28 10:37:45

I need to write a function using regular expressions, func(string), which returns the resulting list as a result of splitting the string. The separators can be enclosed commas with optional spaces or single colons. Look on 'spaces' in example with : and ,. I don't know how to achieve this effect.

Result which I will expect:

>>> func("foo, bar   , sss:s")
['foo', 'bar', 'sss', 's'] 
>>> func("foo"),
['foo']        
>>> func("bla  : bla"),
'bla  ', ' bla'

I have this for now:

import re

def func(t):
    match = re.split(r'[,:]', t)
    return match
Questioner
Epic Opener
Viewed
0
shmulvad 2020-11-28 18:48:06

If I understand you correctly based on your explanation and the examples provided, there can either be commas with a varying number of spaces before and after the comma itself or colons that do not have any spacing in between. If this is the case, the following should work:

def func(str_to_split):
    return re.split(r':| *, *', str_to_split)

The regex ':| *, *' looks for either a single colon or optional space(s) followed by a comma followed by optional space(s) again.