gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 15:21:17 24 4
gpt4 key购买 nike

给出以下字符串...

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


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

最佳答案

您可以使用

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

regex demo .整个模式包含在一个捕获组中,因此所有匹配的子字符串都包含在 String#split 之后的结果数组中.

正则表达式详细信息
  • (_[^_]*_|{[^{}]*}) - 捕获组 1:
  • _[^_]*_ - _ , 0 个或更多字符而不是 _然后是 _
  • | - 或
  • {[^{}]*} - 一个 { , 然后是 { 以外的任何 0 个或多个字符和 }然后是 }

  • 参见 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));

    关于javascript - 在 2 个分隔符之间拆分字符串并包含它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976422/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com