Javascript regex for semicolon not in complex nested quotes
Is there a way that a regex would match all of these instances where the semicolons would not match when in quotes but would match when not in quotes-
";" (match this instance); ";"
';' (match this instance); ';'
"";";" (match this instance); "";";"
';";"' (match this instance); ';";"'
This is just an example and the semicolons can be preceded by numbers letters etc. To provide a bit more context, take for example this case -
'This is a \n ; test "statement;" ;' (match this instance); "This is also a test;'Statement;'"
The (match this instance);
means that that instance of the semicolon should be matched. Also higher levels of "
and '
nesting is possible, so looking for a global solution.
Also it should match if the quotes are escaped with a backslash as so -
\"(match this instance);\"
"\";\""(match this instance);\"(match this instance);\"
You could match the character series that do not constitute a "valid" semi-colon, and then match the semi-colon, ...etc. This way the whole text will be matched, but the semi-colons will be in separate matches:
let regex = /(?:\\.|(["'])(?:\\.|.)*?\1|[^;])+|;/gms;
let test = String.raw`";" (match this instance); ";"
';' (match this instance); ';'
"";";" (match this instance); "";";"
';";"' (match this instance); ';";"'
\"(match this instance);\"
"\";\""(match this instance);\"(match this instance);\"`
let matches = test.match(regex);
console.log(matches);
Whenever a match is just one character (it will be a semi-colon) it is to be considered the actual match you'd be looking for.