pieDragon
pieDragon

Reputation: 7

How to check if a regex has an even number of one character with only 2 characters total?

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

Upvotes: -3

Views: 791

Answers (2)

buondevid
buondevid

Reputation: 728

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.

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522539

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

Upvotes: 1

Related Questions