加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用正则表达式在JavaScript中查找最长的重复子字符串

发布时间:2020-12-14 05:59:29 所属栏目:百科 来源:网络整理
导读:我想在字符串中找到最长的重复字符串,用 JavaScript实现并使用基于正则表达式的方法. 我有一个PHP实现,当直接移植到JavaScript时,不起作用. PHP实现取自问题“Find longest repeating strings?”的答案: preg_match_all('/(?=((.+)(?:.*?2)+))/s',$input,$
我想在字符串中找到最长的重复字符串,用 JavaScript实现并使用基于正则表达式的方法.

我有一个PHP实现,当直接移植到JavaScript时,不起作用.

PHP实现取自问题“Find longest repeating strings?”的答案:

preg_match_all('/(?=((.+)(?:.*?2)+))/s',$input,$matches,PREG_SET_ORDER);

这将填充$matches [0] [X](其中X是$matches [0]的长度),并在$input中找到最长的重复子字符串.我用很多输入字符串对此进行了测试,发现输出是正确的.

JavaScript中最近的直接端口是:

var matches = /(?=((.+)(?:.*?2)+))/.exec(input);

这没有给出正确的结果

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

请注意,对于“xxabcdyy”,您只返回“x”,因为它返回最大长度的第一个字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读