I need a regex pattern to check whether characters present in a string consecutively repeats 3 character in another string

EX:

   var string1 = "HelloWorld";    
   var string2 = "Work";

Here the letters "Wor" in string1 repeats in string2, so it should return true.

Any help on this

5 Answers

2
gurvinder372 On Best Solutions

Use split, substring and includes

var fn = function( string1, string2, matchChars ) {
   return !!string2.split("").find( function(item, index){
       if (index + matchChars <= string2.length ) 
       { 
          return string1.includes( string2.substring( index, index +  matchChars ) ); //check after each turn if the substring from index is included in string1 or not
       }
       return false;
   });
}

console.log( fn("HelloWorld", "Work", 3) );

var fn = function(string1, string2, matchChars) {
  return !!string2.split("").find(function(item, index) {
    if (index + matchChars <= string2.length) {
      return string1.includes(string2.substring(index, matchChars));
    }
    return false;
  });
}

console.log(fn("HelloWorld", "Work", 3));
console.log(fn("HelloWorld", "Wod", 3));

3
Jonny On

Code from https://www.garysieling.com/blog/javascript-function-find-overlap-two-strings:

function findOverlap(a, b) {
  if (b.length === 0) {
    return '';
  }

  if (a.endsWith(b)) {
    return b;
  }

  if (a.indexOf(b) >= 0) {
    return b;
  }

  return findOverlap(a, b.substring(0, b.length - 1));
}

Some test cases:

findOverlap("12345", "aaa") // ""
findOverlap("12345", "12") // "12"
findOverlap("12345", "345") // "345"
findOverlap("12345", "3456") // "345"
findOverlap("12345", "111") // "1"

To solve your particular problem you could:

const haveOverlap = (string1, string2) => findOverlap(string1, string2).length >= 3;
console.log(haveOverlap('HelloWorld', 'Work')); // true
3
gil.fernandes On

Another idea would be to concatenate the two strings, lowercase them and then apply this regular expression:

(\w{3}).+(\1)

function repetitions(s1, s2) {
  const s = s1.toLowerCase() + s2.toLowerCase()
  const r = /(\w{3}).+(\1)/
  const res = r.exec(s)
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));

Here is a more robust version which prevents finding the string repetition in either of the input strings:

function repetitions(s1, s2) {
  const replaceRegex = /(\w{3})(.*)(\1)/;
  const s = s1.toLowerCase().replace(replaceRegex, "$1") + " " + s2.toLowerCase().replace(replaceRegex, "$1");
  const r = /(\w{3}).+?(\1)/;
  const res = r.exec(s);
  return res !== null ? res[1] : "";
}

console.log(repetitions("HelloWorld", "Work"));
console.log(repetitions("HelloWo", "Work"));
console.log(repetitions("HelloWoHello", "Work"));
console.log(repetitions("HelloWoHello", "WorkWork"));
console.log(repetitions("HelloWo", "HelloWork"));

0
Kyle Fairns On

Slightly longer than the other answers here, and nothing too clever about it. Will simply go through and find all matches, which returns an array, and will loop through that array and return true when the longer string contains one of the split strings.

function getAllConsecutives(string, number) {
  let matches = [],
    regex = "";

  for (let i = 0; i < (string.length - number); i++) {
    regex = new RegExp(`\\w{${i}}(\\w{${number}})`);
    matches.push(string.match(regex)[1])
  }

  return matches
}

function areThereConsecutives(string1, string2, number) {
  let short = string1.length < string2.length ? string1 : string2,
    long = string1.length < string2.length ? string2 : string1,
    consecutives = getAllConsecutives(short, number);

  for (let i = 0; i < consecutives.length; i++) {
    if (long.includes(consecutives[i])) {
      return true;
    }
  }

  return false
}

let string1 = "HelloWorld",
  string2 = "Work";

console.log(areThereConsecutives(string1, string2, 3))

0
Salman A On

Your problem is that of finding longest common substring. Here is a JavaScript implementation of that algorithm:

function longestCommonSubstring(string1, string2) {
    var length1 = string1.length,
        length2 = string2.length,
        matchArray = Array(length1).fill().map(function() { return Array(length2).fill(); }),
        matchSize = 0,
        matchList = [],
        i, j;
    for (i = 0; i < length1; i++) {
        for (j = 0; j < length2; j++) {
            if (string1[i] === string2[j]) {
                if (i === 0 || j === 0) {
                    matchArray[i][j] = 1;
                } else {
                    matchArray[i][j] = matchArray[i - 1][j - 1] + 1;
                }
                if (matchArray[i][j] >= matchSize) {
                    if (matchArray[i][j] > matchSize) {
                        matchSize = matchArray[i][j];
                        matchList = [];
                    }
                    matchList.push(string1.substring(i - matchSize + 1, i + 1));
                }
            } else {
                matchArray[i][j] = 0;
            }
        }
    }
    return matchList;
}

console.log(longestCommonSubstring("abcdefghi", "def"));
console.log(longestCommonSubstring("abcdefghi", "*def*"));
console.log(longestCommonSubstring("ababababa", "ab"));
console.log(longestCommonSubstring("ababababa", "ba"));
console.log(longestCommonSubstring("ababababa", "aba"));
console.log(longestCommonSubstring("HelloWorld", "Work"));

Other implementations available here:
Algorithm Implementation/Strings/Longest common substring