You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript正则问题:如何按'{'分割字符串并保留分隔符?

JavaScript 按"{"分割字符串并保留"{"的正确实现

需求说明

需要将包含多个JSON片段的字符串按字符"{"分割,同时保留"{",最终得到如下格式的数组:

[
  "{  \"text\" : \"alinea 1\", \"type\" : \"paragraph\"  }",
  "{  \"text\" : \"alinea 2\", \"type\" : \"paragraph\"  }"
]

现有代码使用了错误的正则表达式,导致输出不符合预期:

("{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }").split(/([?={?>=}]+)/g)

正确实现方式

方法1:使用match直接提取目标片段(推荐)

你的需求本质是提取所有{...}格式的完整片段,用match比split更直接,正则匹配所有以{开头、到}结束的内容即可:

const str = "{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }";
const result = str.match(/{[^}]+}/g);
console.log(result);

输出结果完全符合预期:

[
  "{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  }",
  "{    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }"
]

正则解释:

  • {:匹配字符"{"
  • [^}]+:匹配任意非"}"的字符(至少出现一次,确保覆盖到对应"}"前的所有内容)
  • }:匹配字符"}"
  • g:全局匹配模式,找到所有符合条件的片段

方法2:使用split配合正则实现

如果一定要用split,可以通过正向先行断言定位分割位置,同时过滤无效元素:

const str = "{    \"text\": \"alinea 1\",    \"type\": \"paragraph\"  },  {    \"text\": \"alinea2\",    \"type\": \"paragraph\"  }";
const result = str.split(/,\s*(?={)/g).filter(item => item.trim() !== '');
console.log(result);

输出同样符合预期。正则解释:

  • ,\s*:匹配逗号后面的任意数量空格
  • (?={):正向先行断言,确保分割位置后面紧跟"{"
  • filter:过滤掉可能出现的空字符串

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:47