查找多个实例所需的算法(或正则表达式)
问题描述:
我不确定是否有一种简单的方法来做到这一点,但有没有办法在未知字符串中查找多个实例?例如:查找多个实例所需的算法(或正则表达式)
hellohellohellobyebyebyehello
不知道上面的字符串值,我可以返回的东西,将告诉我,也有“你好” 3个实例和“再见” 3个实例(我不担心!最后的招呼但是我正在寻找连续重复预先感谢
答
"testhellohellohellobyebyebyehello".match(/(.+)\1+/)
这是说:“相匹配的至少1个字符(.+)
序列,然后引用的是第一件事情,我们发现\1
至少一次+
以上
它将返回["hellohellohello", "hello"]
意思hellohellohello匹配。的完整表达式(表达式0), “你好” 匹配表达式1(用其他\1
引用的东西)
警告:。
类似"hahahaha"
将产生["hahahaha", "haha"]
,而不是["hahahaha", "ha"]
。所以你需要使用上面的一些后处理来达到你想要的结果。
答
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
它们总是字典单词吗? – RichardOD 2010-02-24 14:54:18