Kenny
Kenny

Reputation: 11

Splitting a string into multiple groups of strings

I have a string that contains a list of elements, some of which are fixed and some of which are pickable. As an example let's say my string is a grocery list:

"strawberry, raspberry, $2{tomato, sauerkraut, beans},
 potato, $1{{apple, pear}, {orange, banana}}"

And I would like to end up with something like:

["strawberry",
 "raspberry",
 [2, "tomato", "sauerkraut", "beans"],
 "potato",
 [1, ["apple", "pear"], ["orange", "banana"]]

I have no idea how can I tackle the multiple choices here so I'm open to any and all suggestions. Also you can modify the "syntax" (eg "$[num of coices]{list}") and add/remove fluff, it doesn't really matter. The simpler the merrirer! :]

edit: I have bazillions of these lists in the above format and converting them by hand is not an option unless there is no other solution... :(

Thanks!

Upvotes: 1

Views: 300

Answers (2)

Chandu
Chandu

Reputation: 82893

First: I strongly suggest using the JSON based solution that was mentioned by Matt. But for some reason you can't adapt your current code for that, then try this: Note: I haven't tested it for different test cases, but I think it will give you the idea...

  var testString = "strawberry, raspberry, $2{tomato, sauerkraut, beans},  potato, $1{{apple, pear}, {orange, banana}}";
    testString = testString.replace(/\$(\d+){/g, "{$1,");
    testString = testString.replace(/{/g, "[").replace(/}/g, "]");
    testString = testString.replace(/\b/g,'"')
    testString = testString.replace(/(")(\[)/g,'$2$1')
    testString = testString.replace(/(\])(")/g,'$2$1')
    testString = '[' + testString + ']';
    var obj = JSON.parse(testString);
    for(var o in obj)
    {
        alert(typeof obj[o]);
    }

Working Example: http://jsfiddle.net/PcMhw/4/

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

Why are't you using JSON for this?

var list = ["strawberry",
     "raspberry",
     [2, "tomato", "sauerkraut", "beans"],
     "potato",
     [1, ["apple", "pear"], ["orange", "banana"]]];

var str = JSON.stringify(list);
/*
str = '["strawberry","raspberry",[2,"tomato","sauerkraut","beans"],"potato",[1,["apple","pear"],["orange","banana"]]]'
*/

var list2 = JSON.parse(str);
/*
list2 = ["strawberry",
         "raspberry",
         [2,"tomato","sauerkraut","beans"],
         "potato",
         [1, ["apple","pear"], ["orange","banana"]]]
*/

Upvotes: 4

Related Questions