找到任何事物的多个实例所需的算法(或正则表达式)

时间:2010-02-24 14:52:55

标签: javascript regex

我不确定是否有一种简单的方法可以做到这一点,但有没有办法在未知的字符串中找到多个实例?例如:

hellohellohellobyebyebyehello

在不知道上述字符串的值的情况下,我可以返回一些东西,告诉我有3个“hello”实例和3个“bye”实例(我不担心最后一个问候,但是因为我'我正在寻找连续的重复。提前致谢!

5 个答案:

答案 0 :(得分:7)

也许Sequitur算法可以提供帮助:http://sequitur.info/

答案 1 :(得分:4)

s = "hellohellohellobyebyebyehello"
s.replace(/(.+)(\1+)/g, function($0, $1) {
    console.log($1 + " repeated " + ($0.length / $1.length) + " times");
});

答案 2 :(得分:2)

"testhellohellohellobyebyebyehello".match(/(.+)\1+/)

这说:“匹配至少1个字符(.+)的序列,然后引用我们发现的第一件事\1至少一次+或更多。

它将返回["hellohellohello", "hello"],意味着hellohellohello匹配完整表达式(表达式0),“hello”匹配表达式1(我们用\1引用的东西)。

买者:
"hahahaha"这样的内容会产生["hahahaha", "haha"],而不是["hahahaha", "ha"]。所以你需要使用上面的一些后期处理才能得到你想要的结果。

答案 3 :(得分:0)

如果您要查找词典单词,可以在suffix tree中加载词典, 然后逐个考虑你的字符串中的字符并浏览你的树。每次到达一片叶子时,你都会将一个相关的“单词”加1。

答案 4 :(得分:0)

var source = "asdhellohellohellobyehellohellohellohelloasdhello";
var key = "hello";
var len = key.length;
var res = 0, tempres, next;
var last = source.indexOf(key);
while(last != -1)
{
  tempres = 0;
  next = last;
  while(true)
  {
    tempres++;
    next += len;
    last = source.indexOf(key, next);
    if(last != next)
      break;
  }
  res = (tempres > res) ? tempres : res;
}
console.log(res);//4