我想在某个正则表达式上拆分文本,并在原始字符串中获得拆分开始位置的索引。
举个简单的例子:
"bla blabla haha".splitOnRegexWithIndex(whitespaceRegex)
需要的输出是
[["bla", 0], ["blabla", 4], ["haha", 11]]
此处的正则表达式可以是任何内容,而不仅仅是空格,因此分隔符不是固定大小。
拆分是在正则表达式上完成的。我不想使用
indexOf
在起始字符串中查找 "blabla"
因为这将是 O(n2) 复杂性,这在我的场景中是 Not Acceptable 。 最佳答案
这是基于 .exec
的可能实现:
function split_with_offset(str, re) {
if (!re.global) {
throw "no no no no :(";
}
let results = [];
let m, p;
while (p = re.lastIndex, m = re.exec(str)) {
results.push([str.substring(p, m.index), p]);
}
results.push([str.substring(p), p]);
return results;
}
console.log(split_with_offset("bla blabla haha", /\s+/g));
console.log(split_with_offset(" ", /\s+/g));
console.log(split_with_offset("", /\s+/g));
警告:正则表达式必须设置
g
标志。