Created
November 8, 2011 20:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'"]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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