javascript - 在 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))
如您所见,它无法重现所需的数组。
解决方案
您可以使用
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));
推荐阅读
- python-xarray - 尝试计算时小 xarray 对象杀死 Dask 工作人员
- mysql - 为什么 MySQL 没有正确命名我的外键?
- swift - 来自外部 XIB 的 DidSet 崩溃
- go - 如何创建指向reflect.Value的指针
- javascript - 将一些php加密函数转换为nodejs(sha1)
- javascript - useSelector 状态返回 undefined (React-Redux)
- java - 将 Python 控制台输出保存到 Java 变量
- android - React Native Alert.alert() 仅适用于 iOS 和 Android,不适用于 Web
- python-3.x - 在 Python 中将数字转换为二进制
- sql - 检查字符串是否仅在 Transact-SQL 中由字母或数字组成