0

Is regex capable of matching patterns which might be separated by a different pattern?

E.g.: A{3}B{2} would match AAABB. How can I make it match ABABA?

As this is just an example, I am not looking for a way to match all permutations of AAABB, but to learn a generic method. :-)

BadHorsie
  • 14,135
  • 30
  • 117
  • 191
Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
  • You could assert 3 times an A and 2 times a B, then match `[AB]+` – The fourth bird Aug 12 '20 at 10:56
  • 1
    Does this answer your question? [Regex lookahead, lookbehind and atomic groups](https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups) – BadHorsie Aug 12 '20 at 11:36
  • @BadHorsie: Great resource, thanks. I did not yet come up with a solution, but I learned something useful there. :) – Zsolt Szilagyi Aug 12 '20 at 11:48
  • @BadHorsie: After accepting another answer: Yes, your link had the tools needed to solve my task. Knowing the syntax and finding a solution are different beasts though. – Zsolt Szilagyi Aug 12 '20 at 12:08

2 Answers2

1
(?=A{3}B{2})[AB]+

(?=A{3}B{2}) - Positive lookahead of the given string to make sure we have exactly 3 A's and 2 B's. If this results in true then it starts looking for [AB]+ . This strictly matches the AAABB.

https://regex101.com/r/6xcNb7/3

Updated as requested and this should match other permutations.

(?=(?:B*A){3}B*$)|(?=(?:A*B){2}A*$)[AB]{5}
rootkonda
  • 1,700
  • 1
  • 6
  • 11
1

This does the job:

^(?=(?:B*A){3}B*$)(?=(?:A*B){2}A*$)[AB]{5}$

Demo & explanation

Explantion:

^               # beginning of string
  (?=             # positive lookahead, make sure we have after exactly 3 A:
    (?:             # non capture group
      B*              # 0 or more B
      A               # 1 A
    ){3}            # end group, must appear 3 times
    B*              # 0 or more B
    $               # end of string
  )               # end of string
  (?=(?:A*B){2}A*$)     # same explanation as above for exactly 2 B
  [AB]{5}       # we must have 5 A or B
$               # end of string
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Great, thanks! Maybe you could add/copy a high level explanation: As far as I understood: You first look for 3 groups of A with any(\*) Bs in between, then look for 2 groups of Bs with any(\*) As in between, and finally look for a total of 5 A-or-Bs. – Zsolt Szilagyi Aug 12 '20 at 12:06