title: Can we use regular expressions to check if there are an odd number of each type of character?
body: <h3>The problem</h3>
  
  <p>I'm trying to create a regex in which we can check if all letters present in some reference set are present in some other string, but only in odd numbers (1, 3, 5, ...).</p>
  
  <p>Here is a (very) crude image of the <a href="http://en.wikipedia.org/wiki/Deterministic_finite_automaton" rel="nofollow noreferrer" title="Deterministic Finite Automaton">DFA</a> representing the problem:</p>
  
  <p><img src="https://i.stack.imgur.com/AoPH3.png" alt="Odd As and Bs DFA"></p>
  
  <h3>My (broken) solution</h3>
  
  <p>I started using a finite set, <code>{a, b}</code>, so I would essentially check "are there both an odd number of <code>a</code>s and an odd number of <code>b</code>s in the string?"</p>
  
  <p>Unfortunately I did not get far on my own. I first read <a href="https://stackoverflow.com/questions/3698625/regular-expression-for-strings-with-even-number-of-as-and-odd-no-of-bs">this thread</a>, which is remarkably similar to this concept, but was not able to glean an answer from <code>(aa|bb|(ab|ba)(aa|bb)*(ba|ab))*(b|(ab|ba)(bb|aa)*a)</code>. (I understand how it works, but not how to convert it to check odd numbers for <em>both</em> items present.)</p>
  
  <p><strong>Here is what I've come up with so far</strong>: <code>^((ab|ba)(bb|aa)?|(bb|aa)?(ab|ba))+$</code>. This basically checks if there is <code>ab</code> or <code>ba</code> followed by <code>bb</code> or <code>aa</code> or nothing, which would result in <code>ab</code>, <code>ba</code>, <code>abaa</code>, <code>abbb</code>, <code>baaa</code>, or <code>babb</code>. (It also does the reverse of this, checking the double-letter first.) This can then repeat, indefinitely. The problem I have is I cannot seem to adjust it to match the string <code>bbaaba</code> without also matching <code>bbaa</code>.</p>
  
  <p>Additionally, the method above can not be dynamically adjusted to account for <code>{a, b, c}</code>, for example, though I'm willing to forgo this to solve the initial problem.</p>
  
  <h3>Testing</h3>
  
  <p>Here are my test strings and the desired output, with the reasons in parentheses:</p>
  
  <pre><code>"ba"      # True (1a, 1b)
  "abbb"    # True (1a, 3b)
  "bbba"    # True (1a, 3b)
  "bbab"    # True (1a, 3b)
  "ababab"  # True (3a, 3b)
  "bbaaba"  # True (3a, 3b)
  "abb"     # False (2b)
  "aabb"    # False (2a, 2b)
  "aabba"   # False (2b)
  ""        # False (0a, 0b is "even")
  "a"       # False (0b is "even")
  "b"       # False (0a is "even")
  </code></pre>
  
  <h3>Question</h3>
  
  <p>So, is this possible through regex? Or are regular expressions more limited than a DFA? I am aware that it can be done through a basic loop, but this isn't what I'm going for.</p>