1

I have a string which looks like this:

"[segment1][segment2][segment2]"

What I'd like is to be able to split the string into an array, so I'd end up with:

Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3"

I've tried using the string split function, but it doesn't seem to do exactly what I want. I was wondering if anyone has some regex which might help me out?

Thanks in advance

2 Answers 2

4

You could take the slice of the string without the first and last characters, then split on ][:

s = "[segment1][segment2][segment2]"
s[1:-1].split('][')

outputs

['segment1', 'segment2', 'segment2']
Sign up to request clarification or add additional context in comments.

1 Comment

Also, per Tim Pietzcker's answer, you could use s.strip('[]').split(']['), using .strip() instead of the slice [1:-1].
1

You could use the re.split() function:

subject = "[segment1][segment2][segment2]"
reobj = re.compile("[][]+")
result = reobj.split(subject.strip("[]"))
print result

gives you:

['segment1', 'segment2', 'segment2']

Edit: Added a .strip() to avoid an empty first and last element of the resulting list.

Comments

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.