regex match all `,` not inside \[\]

Here is the example string which I have to match:

   var sampleStr = "aaa[bbb=55,zzz=ddd],#ddd[ppp=33,kk=77,rr=fff],tt,ff";

I need to write regex that will match all , characters which is not inside [ ]

so In my sample string I should receive the next , characters:

   - `,` before `#ddd`
   - `,` before `tt`
   - `,` before `ff`

and it should ignore next ,:

  - `,` before `zzz`
  - `,` before `kk`
  - `,` before `rr`

Actually I have no idea how to ignore those , inside [...]. Big thx for any advance



If you can assume that the part inside [] doesn't contain nested [], and the [] are balanced:

var out = content.split(/,(?![^\[\]]*\])/);

(?![^\[\]]*\]) is a negative look-ahead which checks that we are not inside [] with a heuristic. As long as we don't encounter any ] as we consume characters other than [ and ], then we are outside [].

The code above will split the text along those commas , outside brackets [] and return the tokens.


This regex should work


see: DEMO


, is our target comma,

(?![^\[]*?\]) use negative lookahead to guarantee that there is no ] after ,, a trick here is instead of using .* we use [^\[]* to prevent regex match a pattern [...] instead of ..].


One way to avoid commas enclosed in square brackets is to match square brackets first. Example for a replacement:

var result = sampleStr.replace(/([^\[,]*(?:\[[^\]]*\][^\[,]*)*),/g, '$1#');

Other example if you want to split:

var result = sampleStr.match(/(?=[^,])[^\[,]*(?:\[[^\]]*\][^\[,]*)*/g);

The advantage of these approaches is that you don't need to parse all the string until the end with a lookahead for each comma.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.