提供以下字符串...
"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.您可以使用
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演示: