Skip to content

Instantly share code, notes, and snippets.

@scottrippey
Created November 8, 2011 20:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottrippey/1349099 to your computer and use it in GitHub Desktop.
Save scottrippey/1349099 to your computer and use it in GitHub Desktop.
JavaScript that uses a Regex to split a string, ensuring balanced parenthesis and balanced quotes.
var input = "a, b, (c, d), (e, (f, g), h), 'i, j, (k, l), m', 'n, \"o, 'p', q\", r'";
var result = SplitBalanced(input, ",");
// Results:
["a",
" b",
" (c, d)",
" (e, (f, g), h)",
" 'i, j, (k, l), m'",
" 'n \"o, 'p', q\", r'"];
function SplitBalanced(input, split, open, close, toggle, escape) {
// Build the pattern from params with defaults:
var pattern = "([\\s\\S]*?)(e)?(?:(o)|(c)|(t)|(sp)|$)"
.replace("sp", split)
.replace("o", open || "[\\(\\{\\[]")
.replace("c", close || "[\\)\\}\\]]")
.replace("t", toggle || "['\"]")
.replace("e", escape || "[\\\\]");
var r = new RegExp(pattern, "gi");
var stack = [];
var buffer = [];
var results = [];
input.replace(r, function($0,$1,$e,$o,$c,$t,$s,i){
if ($e) { // Escape
buffer.push($1, $s || $o || $c || $t);
return;
}
else if ($o) // Open
stack.push($o);
else if ($c) // Close
stack.pop();
else if ($t) { // Toggle
if (stack[stack.length-1] !== $t)
stack.push($t);
else
stack.pop();
}
else { // Split (if no stack) or EOF
if ($s ? !stack.length : !$1) {
buffer.push($1);
results.push(buffer.join(""));
buffer = [];
return;
}
}
buffer.push($0);
});
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment