Find the longest repeating substring in JavaScript using regular expressions

I would like to find the longest repeating string in a string, implemented in JavaScript and using a regex approach.

I have a PHP implementation that does not work when ported directly to JavaScript.

The PHP implementation is taken from the answer to the question "Find the longest repeating lines?" :

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

It will fill $matches[0][X](where Xis the length $matches[0]) with the longest repeating substring found in $input. I checked this with many input lines and found sure that the output was correct.

Nearest direct port in JavaScript:

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

It does not give the correct results.

input Excepted result matches [0] [X]
======================================================
inputinput             input             input
7inputinput            input             input
inputinput7            input             input
7inputinput7           input             7
XXinputinputYY         input             XX

, , , .

, , , , . , , JavaScript.

, JavaScript? , .

+5
2

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", .

+5

, JS . , .

, , re.exec() "string".match(re) -. Exec, , , , , , ( /g ).

, exec, , ? = , match . ? =

re = /((.+)(?:.*?\2)+)/g

"XXinputinputYY".match(re);

["XX", "inputinput", "YY"]

re.exec("XXinputinputYY");

["XX", "XX", "X"]

, , inputinput . , , , , .

, firebug, , $1, , , - $vars .

0

All Articles