Skip to content

Instantly share code, notes, and snippets.

@baflo
Created June 22, 2018 07:46
Show Gist options
  • Save baflo/d67e71e947483491c6843ddfb5be01ce to your computer and use it in GitHub Desktop.
Save baflo/d67e71e947483491c6843ddfb5be01ce to your computer and use it in GitHub Desktop.
RegExp to find characters not in symmetric (quotes) or asymmetric (brackes) groups
// Create regExp to find commas that are not within double quote, single quote, parantheses, brackets or braces:
const argsSplitRegExp = findCharRegExp(",", { notInSymm: ["\"", "'"], notInAsymm: ["[]", "()", "{}"]});
// Usage (split at found commas):
"age , [32 , 44] , abc".split(argsSplitRegExp);
// RegExp builder
function findCharRegExp(splittingChar, options) {
const notInSymmRE = (char) => `(?=(?:[^\\${char}]*\\${char}[^\\${char}]*\\${char})*[^\\${char}]*$)`;
const notInAsymmRE = (chars) => `(?![^\\${chars[0]}]*\\${chars[1]})`;
options = options || {};
const notInSymm = options.notInSymm || [];
const notInAsymm = options.notInAsymm || [];
let regExpStr;
if (options.preserveWhitespaces) {
regExpStr = splittingChar;
}
else {
regExpStr = `\\s*${splittingChar}\\s*`;
}
notInSymm.forEach((char) => {
regExpStr += notInSymmRE(char);
});
notInAsymm.forEach((chars) => {
regExpStr += notInAsymmRE(chars);
});
return new RegExp(regExpStr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment