Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to parse the string that has multiple delimiters that may be repeating.

The input string is: 

"-abc,-def,ghi-jkl,mno"

Expected return is:

 

["abc", "def", "ghi", "jkl", "mno"]

I tried the belwo code:

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

Gives the output:

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

1 Answer

0 votes
by (36.8k points)

Use the re.findall:

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

Python code:

import re

regex = r"[^,-]+"

string = "-abc,-def,ghi-jkl,mno"

print(re.findall(regex, string))

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

Do check out Python Data Science Course which helps you understand from scratch 

Browse Categories

...