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

如何通过正则直接获取满足双条件的字符串分割结果?

问题

需要分割类似lg:[:after]:hover:color-blue的字符串,规则如下:

  1. 按:作为分隔符拆分内容
  2. 如果内容被[]包裹,要提取括号里的完整内容(哪怕括号里有:)

举几个例子:

  • 输入lg:[:after]:hover:color-blue,期望得到 ['lg', ':after', 'hover', 'color-blue']
  • 其他测试输入:[:after]:hover:color-blue、hover:color-blue、lg:hover:color-blue

目前用正则配合map处理能实现,但觉得map的写法不够优雅,想知道能不能直接通过正则得到最终的分割结果。现有代码如下:

const regex = /(?:([^:\[\]]+)|\[([^\[\]]+)\])/g;

const matches = [...string.matchAll(regex)].map((match) =>
  typeof match[2] !== "undefined" ? match[2] : match[1]
);
解决方案

当然可以,调整正则表达式后,直接用match就能得到目标数组,不需要额外的map处理:

const regex = /(?<=\[)[^\]]+|[^:\[\]]+/g;
const matches = string.match(regex);

正则逻辑说明

  • (?<=\[)[^\]]+:通过正向断言定位到[后面的内容,匹配到]为止,这样就能直接提取括号里的完整内容(包括里面的:)
  • [^:\[\]]+:匹配不包含:、[、]的连续字符,对应那些没有被括号包裹的分隔项

测试所有示例输入,结果都符合预期:

  • lg:[:after]:hover:color-blue → ['lg', ':after', 'hover', 'color-blue']
  • [:after]:hover:color-blue → [':after', 'hover', 'color-blue']
  • hover:color-blue → ['hover', 'color-blue']
  • lg:hover:color-blue → ['lg', 'hover', 'color-blue']

这样代码更简洁,完全满足需求。

内容的提问来源于stack exchange,提问作者Jose Carlos Ramírez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:42:48