Jon*_*ram 5 javascript regex substring repeat
我想在字符串中找到最长的重复字符串,用JavaScript实现并使用基于正则表达式的方法.
我有一个PHP实现,当直接移植到JavaScript时,不起作用.
PHP实现取自对"查找最长重复字符串?"这一问题的回答.:
preg_match_all('/(?=((.+)(?:.*?\2)+))/s', $input, $matches, PREG_SET_ORDER);
Run Code Online (Sandbox Code Playgroud)
这将填充$matches[0][X](在哪里X是长度$matches[0]),找到最长的重复子字符串$input.我用很多输入字符串对此进行了测试,发现输出是正确的.
JavaScript中最近的直接端口是:
var matches = /(?=((.+)(?:.*?\2)+))/.exec(input);
Run Code Online (Sandbox Code Playgroud)
这没有给出正确的结果
input Excepted result matches[0][X] ====================================================== inputinput input input 7inputinput input input inputinput7 input input 7inputinput7 input 7 XXinputinputYY input XX
我对正则表达式不太熟悉,无法理解这里使用的正则表达式是做什么的.
我确实可以实现一些算法来找到最长的重复子串.在我尝试这样做之前,我希望不同的正则表达式能够在JavaScript中产生正确的结果.
可以修改上面的正则表达式,以便在JavaScript中返回预期的输出吗?我承认,这可能不可能在一个班轮.
Javascript匹配仅返回第一个匹配项 - 您必须循环才能找到多个结果.一点点测试表明这得到了预期的结果:
function maxRepeat(input) {
var reg = /(?=((.+)(?:.*?\2)+))/g;
var sub = ""; //somewhere to stick temp results
var maxstr = ""; // our maximum length repeated string
reg.lastIndex = 0; // because reg previously existed, we may need to reset this
sub = reg.exec(input); // find the first repeated string
while (!(sub == null)){
if ((!(sub == null)) && (sub[2].length > maxstr.length)){
maxstr = sub[2];
}
sub = reg.exec(input);
reg.lastIndex++; // start searching from the next position
}
return maxstr;
}
// I'm logging to console for convenience
console.log(maxRepeat("aabcd")); //aa
console.log(maxRepeat("inputinput")); //input
console.log(maxRepeat("7inputinput")); //input
console.log(maxRepeat("inputinput7")); //input
console.log(maxRepeat("7inputinput7")); //input
console.log(maxRepeat("xxabcdyy")); //x
console.log(maxRepeat("XXinputinputYY")); //input
Run Code Online (Sandbox Code Playgroud)
请注意,对于"xxabcdyy",您只返回"x",因为它返回最大长度的第一个字符串.