在两个定界符之间分割字符串,并包括它们

提供以下字符串...

"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))

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

评论
蛋小疼
蛋小疼

You can use the following regex and filter the undefined values.

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).filter(Boolean))
.as-console-wrapper { max-height: 100% !important; top: 0; }
点赞
评论
木槿花*
木槿花*

您可以使用

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

See the regex demo. The whole pattern is enclosed in a capturing group, so all matching substrings are included in the resulting array after String#split.

正则表达式详细信息

  • (_[^_]*_|{[^{}]*}) - Capturing group 1:
    • _[^_]*_ - _, 0 or more chars other than _ and then a _
    • | - or
    • {[^{}]*} - a {, then any 0 or more chars other than { and } and then 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));
点赞
评论