【发布时间】:2019-05-23 18:45:45
【问题描述】:
我找不到以下问题的解决方案,这让我抓狂。我需要在另一个字符串中找到一个字符串的每个位置。
这是我想出的:
function getMatchIndices(regex, str) {
let result = [];
let match;
let regex = new RegExp(regex, 'g');
while (match = regex.exec(str))
result.push(match.index);
return result;
}
const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';
const indices = getMatchIndices(new RegExp(rule, "g"), line);
console.log(indices);
现在,问题是这与在其他两个匹配中间形成的 aba 不匹配...
这是一个说明问题的图片:
有什么想法吗?
【问题讨论】:
-
我同意你的问题是重复的,除非你真的需要让你的“规则”成为一个正则表达式,而不仅仅是一个字符串。
标签: javascript regex match