Created
June 22, 2018 07:46
-
-
Save baflo/d67e71e947483491c6843ddfb5be01ce to your computer and use it in GitHub Desktop.
RegExp to find characters not in symmetric (quotes) or asymmetric (brackes) groups
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
// 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