views:

276

answers:

3
'{5}<blah>{0}</blah>'

i want to turn that into:

['{5}', '<blah>', '{0}', '</blah>']

i currently use: ________.split(/({.*?})/);

but this fails when curly brace is the first character as in the case:

'{0}<blah>'

which gets turned into: ['', '{0}', '<blah>'] ... a 3 element array, not a 2

what's wrong with my regex?

Thanks!

+5  A: 

There's nothing wrong with your regex, but there's an issue with how you're using split. Split returns an array based on a delimiter, so if the delimiter is FIRST, it gives you the stuff to the left and right of the split item.

Just check to see if the first item == '' and remove it if it is.

Stefan Kendall
You read my answer while I was typing it! :)
Paul McGuire
Mine too! Honor doesn't exist on teh Interwebs ;)
roosteronacid
I'm a fast typer, and I'm a pretty prominent psychic in the midwest. 1 + 2 == stolen SO responses!
Stefan Kendall
A: 

This should do it:

split(/((?!^)\{.*?\})/)

The negative lookahead -- (?!^) -- succeeds iff the match does not start at the beginning of the string.

Alan Moore
A: 

What do you think of:

'{5}<blah>{0}</blah>'.split(/{([^}]+)}/g)

The value of the curly blocks are every 2 items from the item 1.

Mic