0

For example, I could want to split "Hello>>>World!!!!2]]splitting" into ["Hello", "World","2","splitting"]. It doesn't need to be ^that^, but I want to split a string with multiple (say 5) delimiters. Thanks.

EDIT: I also want to keep the delimiter, making it ["Hello", ">>>", "World", "!!!!", "2", "]]", "splitting"]

Here's what I've tried:

>>> string = "Hello>>>World!!!!2]]splitting"
>>> import re
>>> re.split("(\W)>>>|!!!!|]]", string)
['Hello>>>World', None, '2', None, 'splitting']

(I'm new at Regex)

3
  • 1
    re.split? Commented Sep 30, 2015 at 0:47
  • Can you show your code please with any error messages you are receiving? Also, it would help if you can clearly indicate what parts of your code you're having difficulty with. Commented Sep 30, 2015 at 0:49
  • @idjaw I'm uploading it, just a sec... Commented Sep 30, 2015 at 0:50

2 Answers 2

8

To do this using re.split you can do:

re.split(r'(>+|!+|]+)', string)

Explaining this briefly:

  • You split on one or more occurrences of the different delimiters (>, !, ]).
  • In order to include the delimiters in the result, you put the pattern in a capturing group by putting parens around it.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the explanation
So doesn't that mean that re.split(r'(\+)', string) would split the spaces and keep the spaces?
@Henry Yep, try it, re.split(r'( )', 'the quick brown fox')
3
import re

a = 'Hello>>>World!!!!2]]splitting'

print(re.findall('\W+|\w+',a))

['Hello', '>>>', 'World', '!!!!', '2', ']]', 'splitting']

What you're doing is finding all word characters or non word characters.

2 Comments

What if it was something like splitting spaces and newlines and keeping both too?
Just change the regex pattern. You got an example for that? newlines would be \n and \ + for spaces

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.