jgr208 jgr208 - 1 year ago 51
Javascript Question

Regex keeps finding character I want matched along with previous character

I have the following regex in

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


The result would be that
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 Source

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:


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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download