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
  • 579
  • 2
  • 5
  • 26

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
  • 16,363
  • 2
  • 17
  • 35
1

You can filter the result like this

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