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
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.