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

标签 javascript regex

给出以下字符串...

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

    相关文章:

    javascript - 如何在网页中添加自定义右键菜单?

    javascript - 在 Jquery 中将标志从一个事件传递到另一个事件

    javascript - 如何使用 Iron Router 获取 domain.com/keyword 中的 'keyword'

    javascript - jQuery/javascript 问题,点击处理程序是异步执行的吗?

    ruby - 排除某些单词的正则表达式

    javascript - 从 Javascript 中的字符串获取 URL 值

    regex - 创建表期间解析 Hive 中的时间戳

    regex - sed regex命令输出以html结尾的行?

    javascript - 转义字符串字符而无需手动转义它们

    javascript - 单击按钮时的新输入