查找多个实例所需的算法(或正则表达式)

问题描述:

我不确定是否有一种简单的方法来做到这一点,但有没有办法在未知字符串中查找多个实例?例如:查找多个实例所需的算法(或正则表达式)

hellohellohellobyebyebyehello 

不知道上面的字符串值,我可以返回的东西,将告诉我,也有“你好” 3个实例和“再见” 3个实例(我不担心!最后的招呼但是我正在寻找连续重复预先感谢

+0

它们总是字典单词吗? – RichardOD 2010-02-24 14:54:18

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

这是说:“相匹配的至少1个字符(.+)序列,然后引用的是第一件事情,我们发现\1至少一次+以上

它将返回["hellohellohello", "hello"]意思hellohellohello匹配。的完整表达式(表达式0), “你好” 匹配表达式1(用其他\1引用的东西)

警告:。
类似"hahahaha"将产生["hahahaha", "haha"],而不是["hahahaha", "ha"]。所以你需要使用上面的一些后处理来达到你想要的结果。

也许不合逻辑算法可以帮助:http://sequitur.info/

+0

+1。有趣。 – RichardOD 2010-02-24 14:56:57

如果你正在寻找弥补字典的话,你可以在suffix tree加载词库, 然后逐一考虑你的字符串的字符,并去thr呃你的树。每次到达一片叶子时,你都会增加一个相关的“单词”。

+0

前缀树就足够了,甚至在JavaScript中也很容易实现。 – jkff 2010-02-24 15:10:20

+0

我删除了我所说的JavaScript,因为我不是专家......并且真的,前缀树已经足够,更容易实现,但没有进行优化 – PierrOz 2010-02-24 15:22:37

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 

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

+1因为创新。做出第一个'+'nongreedy('/(。+?)(\ 1 +)/'),或者重复2次hellohello而不是hello重复4次(如果有4个)你好在字符串中) – Amarghosh 2010-02-24 15:39:32