【问题标题】:Finding ALL positions of a string within another string [duplicate]在另一个字符串中查找一个字符串的所有位置[重复]
【发布时间】: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


【解决方案1】:

我意识到这不是正则表达式解决方案。所以它可能不是你需要的。

希望对你有帮助。

function getMatchIndices(r, str) {
  const indices = [];
  str.split('').forEach((v,i) => {
    if(r === str.substring(i,i+r.length)) {
      indices.push(i);
    }
  });
  return indices;
}

const line = "aabaabbaababaababaaabaabaaabaabbabaababa";
const rule = 'aba';

const indices = getMatchIndices(rule, line);

console.log(indices);

【讨论】:

  • 不是正则表达式,意味着它有 99% 的可能性是更好的解决方案。
  • 大声笑,我听到了。正则表达式可以很快得到超级混淆。
  • 非常感谢!我不敢相信我自己没有想到这一点。对于我的用例,这同样适用。
  • 很高兴它有帮助,编码愉快。
猜你喜欢
  • 2011-01-23
  • 2018-10-03
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多