Home > Mobile >  How do you split by comma everything that is outside of brackets with regex in javascript?
How do you split by comma everything that is outside of brackets with regex in javascript?

Time:01-27

I need to separate a string by commas except what is inside square brackets

Example

Dog[Food, Toys], Cat[Movies, brush]

I want to get

"Dog[Food,Toys]","Cat[Movies,Brush]"]

Thanks

CodePudding user response:

You can use below Regex to spilt the string. This regex finds any comma after closing square bracket.

,(?<=],)

Test link

CodePudding user response:

A more reliable and also whitespace aware approach which especially takes heothesennoc's comment on Rajesh's solution ...

"This won't work if there exists an item without brackets, e.g. Dog, Cat[Movies, Brush], Horse[Stable] – heothesennoc"

... into account has to feature a full lookaround, a negative lookbehind and a negative lookahead.

The pattern would be as follows ... (?<![[^]] )\s*,\s*(?!]). A description is provided with the link.

// see ... [https://regex101.com/r/yhyMOw/2]
const regXSplit = /(?<!\[[^\]] )\s*,\s*(?!\])/;

console.log([

  'Dog[Food, Toys], Fish,Cat[Movies, brush] ,Hamster[Litter, Food, Toys]',
  'Dog[Food, Toys],Bird, Cat[Movies, brush], Hamster[Litter, Food, Toys]',
  'Dog[Food, Toys],Mouse,Cat[Movies, brush] , Hamster[Litter, Food, Toys]',
  'Dog[Food, Toys] ,Horse, Cat[Movies, brush],Hamster[Litter, Food, Toys]',

].map(str => str.split(regXSplit)));
.as-console-wrapper { min-height: 100%!important; top: 0; }

  •  Tags:  
  • Related