0

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
shmulvad
  • 636
  • 4
  • 15
  • unclear question. – dahiya_boy Nov 28 '20 at 10:42
  • Does this answer your question? [Split Strings into words with multiple word boundary delimiters](https://stackoverflow.com/questions/1059559/split-strings-into-words-with-multiple-word-boundary-delimiters) – CodeAllDay Nov 28 '20 at 11:05

2 Answers2

2

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.

shmulvad
  • 636
  • 4
  • 15
0

This could be a good solution:

def trim(text):
    return str(text).strip()

result = list(map(trim, match))
Omri Shayo
  • 64
  • 8