-3

I want to be able to use a file containing only A's and B's and using only a regex be able to only allow sections with an even number of A's and either odd or even for B's. The A's can be separated by B's and don't have to be in sets of 2.

Here are some examples:

 AABBABA -> pass
 BABBAB  -> pass
 BABAAB  -> fail
 BABBBA  -> pass

2 Answers2

1

The following regex pattern seems to work well:

^B*((AB*){2})*B*$

This matches the pattern AB*AB* zero or more times in the middle, with optional B on both ends. Check the demo to see it working correctly.

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Here you go, it matches only with an even number of A:

/^[^A]*(A[^A]*A[^A]*)*$/gm

If you don't need case sensitive, just put i flag like /gmi.

buondevid
  • 347
  • 2
  • 7