tags:

views:

43

answers:

2

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

+1  A: 

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.

Tim Pietzcker
+3  A: 

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']
Isaac
Also, per Tim Pietzcker's answer, you could use `s.strip('[]').split('][')`, using `.strip()` instead of the slice `[1:-1]`.
Isaac