花括号内的逗号分割值正则表达式javascript

时间:2018-01-05 13:20:58

标签: javascript regex

我有一个字符串看起来像这样。

var str = "RR,target_value,006EI4ZXZALFXAT2E4AHX2O6V,006EI4ZXZALFXAT2E4AHX2O6V,dynamic,{\"(MEASURES_DIMENSION)\":\"006EI4ZXZALFXAT2E4AHX2O6V\",\"ZR_ITEM__ZR_BRAND\":\"0000000201\"},cell_selection,34932,#FFFFFF,,25,[{\"color\":\"#566C6C\",\"from\":\"10\",\"to\":\"50\",\"icon\":\"fa://minus-with-square\",\"size\":\"30\",\"angle\":\"45\"}]";

var array = str.split(/,(?=[^\]]*(?:\[|$))/); 我将字符串拆分为数组。所以输出是这样的。

["RR","target_value","006EI4ZXZALFXAT2E4AHX2O6V","006EI4ZXZALFXAT2E4AHX2O6V","dynamic","{\"(MEASURES_DIMENSION)\":\"006EI4ZXZALFXAT2E4AHX2O6V\"","\"ZR_ITEM__ZR_BRAND\":\"0000000201\"}","cell_selection","34932","#FFFFFF","","25","[{\"color\":\"#566C6C\",\"from\":\"10\",\"to\":\"50\",\"icon\":\"fa://minus-with-square\",\"size\":\"30\",\"angle\":\"45\"}]"]

但它是基于花括号内的逗号分裂。但它不应该那样。我需要完整的字符串,不管花括号里面是什么。

2 个答案:

答案 0 :(得分:1)

这是匹配正则表达式

\{[^}]*\}|[^,.\s\[\]]+

不确定是否是您的期望,演示:https://regex101.com/r/Ce5QqV/2

答案 1 :(得分:0)

您可以使用另一个positive lookahead,就像您用于方括号的那个:

(?=[^}]*(?:{|$))

你的正则表达式如下:

,(?=[^\]]*(?:\[|$))(?=[^}]*(?:{|$))

var str = "RR,target_value,006EI4ZXZALFXAT2E4AHX2O6V,006EI4ZXZALFXAT2E4AHX2O6V,dynamic,{\"(MEASURES_DIMENSION)\":\"006EI4ZXZALFXAT2E4AHX2O6V\",\"ZR_ITEM__ZR_BRAND\":\"0000000201\"},cell_selection,34932,#FFFFFF,,25,[{\"color\":\"#566C6C\",\"from\":\"10\",\"to\":\"50\",\"icon\":\"fa://minus-with-square\",\"size\":\"30\",\"angle\":\"45\"}]";
console.log(str.split(/,(?=[^\]]*(?:\[|$))(?=[^}]*(?:{|$))/));