1

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'.

0

1 Answer 1

5

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")
Sign up to request clarification or add additional context in comments.

3 Comments

@MartijnPieters. OOPs, mixed up with Java.
Yea, I used the split method previously, but the issue came up of having a space after the ,, which would mess up the result I wanted.
@RohitJain Awesome, worked. I'll accept when the ticker lets me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.