jgr208 jgr208 - 1 month ago 6
Javascript Question

Regex keeps finding character I want matched along with previous character

I have the following regex in

javascript
for a split operation since I can't do a negative look behind to find any delimiters
,
in a string that is not proceeded by one or more escape characters of
\
.

[^\\],


The regex works fine for finding where the commas not proceeded by
\
are, but also finds the character that proceeds the comma as a match and thus splits the string incorrectly.

For example if I had the string

hello\,there,are


The result would be that
e,
matches my regex and not just
,
. Making the split string array read

[hello\,ther] [are]


Why does the regex I am using keep finding the comma and the proceeding character instead of only matching the comma?

Answer

You cannot use split here because you'd need a lookbehind that JS regex does not support. Use a match with appropriate regex. Like the one below:

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

See the regex demo.

The pattern matches 1 or more (+) sequences of any char other than , and \ ([^\\,]) or (|) any escaped character (excluding linebreak chars) with \\.

JS demo:

var regex = /(?:[^\\,]|\\.)+/g;
var str = "hello\\,there,are";
var res = str.match(regex);
console.log(res);

Comments