首页 > 解决方案 > 在 2 个分隔符之间拆分字符串并包含它们

问题描述

给出以下字符串...

"Here is my very _special string_ with {different} types of _delimiters_ that might even {repeat a few times}."

...如何使用 2 个分隔符(“_”、“{ 和 }”)将其拆分为一个数组,但还要将分隔符保留在数组的每个元素中?

目标是:

[
  "Here is my very ", 
  "_special string_", 
  " with ", 
  "{different}", 
  " types of ", 
  "_delimiters_", 
  "that might even ", 
  "{repeat a few times}", 
  "."
]

我最好的选择是:

let myText = "Here is my very _special string_ with {different} types of _delimiters_ that might even {repeat a few times}."

console.log(myText.split(/(?=_|{|})/g))

如您所见,它无法重现所需的数组。

标签: javascriptregex

解决方案


您可以使用

s.split(/(_[^_]*_|{[^{}]*})/).filter(Boolean)

请参阅正则表达式演示。整个模式包含在一个捕获组中,因此所有匹配的子字符串都包含在结果数组中String#split

正则表达式详细信息

  • (_[^_]*_|{[^{}]*})- 捕获组 1:
    • _[^_]*_- _, 0 个或多个字符_,然后是 a_
    • |- 或者
    • {[^{}]*}- a ,然后是除and之外的{任何 0 个或多个字符,然后是 a{}}

见 JS 演示:

var s = "Here is my very _special string_ with {different} types of _delimiters_ that might even {repeat a few times}.";
console.log(s.split(/(_[^_]*_|{[^{}]*})/).filter(Boolean));


推荐阅读