You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

JavaScript正则:避免拆分花括号内逗号的字符串分割问题

Fixing Split to Preserve Braced Content

The issue with your current regex is that it only accounts for square brackets ([]) but doesn't handle curly braces ({}), so commas inside the JSON-like braced string get split apart. To fix this, we need a regex that targets only commas outside of balanced curly braces (and optionally square brackets, since your string also includes an array).

Solution Regex

Use this pattern for splitting:

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

How It Works

Let’s break down the logic step by step:

  • ,: Matches the comma we want to split on.
  • (?= : Starts a positive lookahead to validate the comma’s context:
    • (?:[^{}]*{[^{}]*})*: Matches any number of balanced curly brace pairs — this skips over all content inside valid {} blocks entirely.
    • [^{}]*$: Ensures that after those balanced pairs, there are no unclosed curly braces left until the end of the string.

This guarantees we only split commas that are not inside any curly brace blocks.

Full Code Example

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(/,(?=(?:[^{}]*{[^{}]*})*[^{}]*$)/);

// Check the result: the 6th element (index 5) is the full braced string
console.log(array[5]); 
// Output: {"(MEASURES_DIMENSION)":"006EI4ZXZALFXAT2E4AHX2O6V","ZR_ITEM__ZR_BRAND":"0000000201"}

Handling Square Brackets Too

If you also want to avoid splitting commas inside square brackets (like in the final array in your string), extend the regex to account for both balanced braces and brackets:

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

This version will skip commas inside both {} and [] blocks, keeping all your JSON-like structures intact.

内容的提问来源于stack exchange,提问作者htoniv

火山引擎 最新活动