1

Hello stackoverflow community!

I want to match all (same-length) string permutations of AAB, so I want to match:

AAB
BAA
ABA

but not:

ABB
AB
AABA

I have already found many sources mentioning lookarounds and backreferences at similar questions such as [1] or [2] but I am struggling with repeated characters such as "AA".

I have tried:

^(?=[AAB]{3}$)(?!.*(.).*\1).*$
^([AAB])(?!\1)([AAB])(?!\1|\2)([AAB])(?!\1|\2|\3)$

Do you have any ideas on that? Thanks in advance!

Community
  • 1
  • 1
d053420
  • 13
  • 2
  • I have a feeling this may be an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Regex isn't really the best way to do something like this. Unless you want something as simple as `^(AAB|BAA|ABA)$`. – R Nar Aug 08 '16 at 15:23

1 Answers1

1

Here's a pattern that matches the three permutations:

^(?=.*B)(?=(.*A){2})...$

This pattern requires that:

  • the length of the string is 3 (...)
  • there is one B (the (?=.*B) lookahead)
  • there are two As (the (?=(.*A){2}) lookahead)

But wouldn't the much simpler ^(AAB|ABA|BAA)$ also work?

Cristian Lupascu
  • 39,078
  • 16
  • 100
  • 137