Find longest repeating substring in JavaScript using regular expressions

后端 未结 2 777
有刺的猬
有刺的猬 2021-01-13 08:59

I\'d like to find the longest repeating string within a string, implemented in JavaScript and using a regular-expression based approach.

I have an PHP implementation

2条回答
  •  无人共我
    2021-01-13 09:29

    Javascript matches only return the first match -- you have to loop in order to find multiple results. A little testing shows this gets the expected results:

    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
    

    Note that for "xxabcdyy" you only get "x" back, as it returns the first string of maximum length.

提交回复
热议问题