0

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.

thawtk
  • 11
  • Are you looking for pattern or just a substring? For example, does your pattern include quantifiers and metacharacters (`.` for any character, etc.) – raina77ow Oct 14 '20 at 00:01
  • This - https://stackoverflow.com/questions/18029487/how-to-get-all-possible-overlapping-matches-for-a-string - looks like a superset of this task, and code in its accepted answer can be simplified to do count only. – raina77ow Oct 14 '20 at 00:04
  • well, I wanted the pattern(yes, sorry for the wrong choice of words) to consist of anything but spaces. It is going to be something I want the users to specify, that's why I didnt want to hardcode any rules... – thawtk Oct 14 '20 at 00:05
  • Please check the code and try to use it; if there will be any specific questions, post them. :) And welcome onboard! – raina77ow Oct 14 '20 at 00:08
  • This might be a more useful dup...https://stackoverflow.com/a/4009768/294949 – danh Oct 14 '20 at 00:09
  • @danh How? The accepted answer there doesn't even mention overlaps (and is essentially the same as OP used). The one used to close it, however, shows lookaheads as another good option. – raina77ow Oct 14 '20 at 00:11
  • Oh wow, thank you both, I'll take a look at the links! :-) – thawtk Oct 14 '20 at 00:12

0 Answers0