在 2 个分隔符之间拆分字符串并包含它们

dan*_*iar 5 javascript regex

给出以下字符串...

"Here is my very _special string_ with {different} types of _delimiters_ that might even {repeat a few times}."
Run Code Online (Sandbox Code Playgroud)

...如何使用 2 个分隔符(“_”、“{ 和 }”)将它拆分成一个数组,同时在数组的每个元素中保留分隔符?

目标是:

[
  "Here is my very ", 
  "_special string_", 
  " with ", 
  "{different}", 
  " types of ", 
  "_delimiters_", 
  "that might even ", 
  "{repeat a few times}", 
  "."
]
Run Code Online (Sandbox Code Playgroud)

我最好的选择是:

"Here is my very _special string_ with {different} types of _delimiters_ that might even {repeat a few times}."
Run Code Online (Sandbox Code Playgroud)

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

Wik*_*żew 5

您可以使用

s.split(/(_[^_]*_|{[^{}]*})/).filter(Boolean)
Run Code Online (Sandbox Code Playgroud)

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

正则表达式详情

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

见JS演示:

s.split(/(_[^_]*_|{[^{}]*})/).filter(Boolean)
Run Code Online (Sandbox Code Playgroud)