1

I need to explain a little: I want to find how many "abab" exists in "ababab" string.

But skipping is valid like

[abab]ab

[aba]ba[b]

[ab]ab[ab]

[a]ba[bab]

these are all valid, my attempt was to use < /\w*?a\w*?b\w*?a\w*?b/g > which of course did not work. What should I do?

Python solutions are also good for me, I thought regex would be good for this.

Edit: Marked similar question is quite different to my question

  • But it doesn't work, I counted 4 to you in the post, this code returns 2 – Kayra Uckilinc Apr 24 '21 at 21:45
  • 1
    Right, still, you need a way to get overlapping matches with the support of getting multiple matches that share the same start position. I think there are 5 matches, in fact, see https://ideone.com/YZxOf2 – Wiktor Stribiżew Apr 24 '21 at 21:58

1 Answers1

1

For the little testing I have done, this works:

def abab(to_check):
    return is_a(0, to_check)


def is_a(i, to_check):
    count = 0
    for index, c in enumerate(to_check):
        if c == 'a':
            count = count + is_b(i + 1, to_check[index + 1:])
    return count


def is_b(i, to_check):
    count = 0
    for index, c in enumerate(to_check):
        if c == 'b':
            if i == 2:
                count = count + 1
            else:
                count = count + is_a(i, to_check[index + 1:])
    return count


print(abab("ababab"))
Tytrox
  • 483
  • 2
  • 10