0

In Javascript, I am trying to split the following string

var s1 = "(-infinity, -3],(-3,-2),[1,infinity)";

into an array

["(-infinity, -3]","(-3,-2)","[1,infinity)"]

by using this statement

s1.split(/(?=[\]\)]),/);

to explain, I want to split the string by commas that follow a closing square bracket or parenthesis. I use the Look Ahead (?=[\]\)]), to do so, but it doesn't match any commas. When I change it to (?![\]\)]),, it matches every commas. Please suggest what is the problem in my regex.

asinkxcoswt
  • 2,252
  • 5
  • 29
  • 57

1 Answers1

3

Your logic is backwards. (?=...) is a look-ahead group, not a look-behind. This means that s1.split(/(?=[\]\)]),/); matches only if the next character is simultaneously ] or ) and ,, which is impossible.

Try this instead:

s1.split(/,(?=[\[\(])/);
elixenide
  • 44,308
  • 16
  • 74
  • 100