I am creating a recursive js function which basically parses a string. I do not get to choose the syntax of the string, so i can’t change that. its delimited by a “, ” which works fine, expect when they are in parenthesis, it needs to ignore inside of the parentheses, in this case it needs to split after the parenthesis. Here is an example.
String: "h5, h7, (h5, h7, r3)7, h9"
And it needs to be transformed into an array of strings that looks like
array( "h5", "h7", "(h5, h7, r3)7", "h9" );
I know there is probably a way to do it with regex, and I have a very basic regex knowledge, but I can’t figure it out. If it helps here is the js code I have.
cols = pattern.split(',');// This is where the regex would go.
$.each(cols, function(index, val){
val = $.trim(val);
var type = "";
var ctr = 0;
for(ctr = 0; ctr < val.length && isAlpha(val[ctr]); ctr++)
type += val[ctr];
if(val[0] == "("){
open = 1;
substr = "";
i = 1;
for(; i < val.length && open > 0; i++ ){
if(val[i] == ")"){
open--;
}
else
substr += val[i];
}
var repeater = val.substr(i);
if(isNumeric(repeater)){
for(j=0; j < repeater; j++){
colLen += updateRow(row, substr, false);
}
}
else{
$('#'+row).append('<a href="" >SE</a>');
colLen++;
}
}
// If it doesn't start with a parenthesis, do print it as usual
Obviously there is a lot more code, but that is the relevant part.
Sorry If i formatted it wrong, this is my first question.
Here are a couple brute force methods that work:
Method 1: Match the parenthesized portions and temporarily replace the commas inside with something else so you can then split on comma and then put the commas back in the parenthesized pieces.
Method 2: Split the whole string by a comma and then puts the parenthesized pieces back together again:
You can see both of these work here: http://jsfiddle.net/jfriend00/cs224/