1

I'm trying to parse a string that has multiple delimiters which may be repeating.

Input string: "-abc,-def,ghi-jkl,mno"

Expected return: ["abc", "def", "ghi", "jkl", "mno"]

I've tried

re.split(",|-", string)

But the return is:

['', 'abc', '', 'def', 'ghi', 'jkl', 'mno']
Borisw37
  • 739
  • 2
  • 7
  • 30

2 Answers2

4

Use re.findall:

re.findall(r'[^-,]+', string)

See proof

Python code:

import re
regex = r"[^,-]+"
string = "-abc,-def,ghi-jkl,mno"
print(re.findall(regex, string))

Result: ['abc', 'def', 'ghi', 'jkl', 'mno']

Ryszard Czech
  • 18,032
  • 4
  • 24
  • 37
1

You can filter the result like this

>>> list(filter(len, re.split(r"[,|-]+", s)))
['abc', 'def', 'ghi', 'jkl', 'mno']
DevCl9
  • 298
  • 1
  • 9