I am trying to evaluate user input and I am looking for all occurrences of a given pattern(e.g. 'zz') in a given string. I have found plethora of answers here but I would ideally want my function to detect all occurrences, including the ones that overlap. So, for instance in 'zzzyzyzz', 'zz' appears 3 times - twice in 'zzz' and once at the end. I tried attacking this problem from different angles and the best solution I came up with does not cover the overlapping cases..
findOverlappingOcc(string, substring) {
const regex = new RegExp(`${substring}(?<=${substring})`, 'g');
return (string.match(regex) || [])).length;
}
I am not super confident about my regex skills and despite somewhat understanding the idea above(looking back), I do not exactly know how to improve/modify it.. Ideally I'd not use regular expressions and opt for e.g. .split().length -1
, but then from what I found out, it does not quite work with overlapping substrings.
Any help would be highly appreciated, ty.