Reputation:
Say I have a string "Dogs,cats"
. If I do re.split(r'[,]*', 'Dogs,cats')
, then I get ['Dogs', 'cats']
, and this is good, but if I get 'Dogs, cats'
, then I get a list ['Dogs', ' cats']
and this is bad. How to I make my regex pattern match either having a comma with no space or with a space to still give me ['Dogs', 'cats']
?
I tried re.split(r'[\s,]*', 'Dogs,cats')
and while that works here, it gives an unwanted splitting in the cases where I have a say, 'dogs,cats are Happy'
.
Upvotes: 1
Views: 2600
Reputation: 213261
Your first case doesn't even need a regex. You can simply do:
"Dogs,Cats".split(",")
For your 2nd case, you can use:
re.split(r',\s*', "Dogs, Cats")
Upvotes: 5