J Aronson
J Aronson

Reputation: 78

Regex Splitting with Negative Lookbehind

The string I am trying to split:

string1, string2, string\,3, string4

I want to split the above string on each comma, except when the comma is escaped with a backslash.

I am unable to utilize negative lookbehind in my JavaScript.

My attempt:

var splits = "string1, string2, string\,3, string4".split("(?<!\\\\),");

None of the commas are being recognized.

Potential solutions: after research, I stumbled across this SO question. However, I don't understand the workarounds well enough to change the above code to the replace the use case.

Upvotes: 5

Views: 695

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

s.match(/(?:[^,\\]|\\.)+/g)

See the regex demo. It will match 1 or more chars other than comma and backslash, or any char that is escaped with a literal backslash.

Note that the string literal should have a double backslash to define a literal backslash.

var splits = "string1, string2, string\\,3, string4".match(/(?:[^,\\]|\\.)+/g);
console.log(splits);

Upvotes: 5

Related Questions