从这种文字开始;
var txt = "hello [a14] world, and [b74] some more [h85], ..."
我期待的结果
var arr =
[ "hello "
, "[a14]"
, " world, and "
, "[b74]"
, " some more "
, "[h85]"
, ", ..."
]
到目前为止我已经尝试过,但是掌握正则表达式对我来说仍然很难......
let txt = "hello [a14] world, and [b74] some more [h85], ..."
let arr = txt.match(/(\[(.*?)\])|(.*?)/g)
console.log( arr )
.as-console-wrapper { max-height: 100% !important; top: 0; }
最佳答案
您还可以尝试拆分环视:
var text = "hello [a14] world, and [b74] some more [h85], ...";
var arr = text.split(/(?=\[)|(?<=\])/);
console.log(arr);
这里的逻辑是,只要后面是[
,就拆分字符串。或 ]
之前的内容.请注意,lookarounds 的宽度为零,因此模式 (?=\[)|(?<=\])
匹配但在拆分时实际上不消耗输入中的任何文本。
关于javascript - 如何使用正则表达式匹配拆分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66148804/