title: Optional Group Capture with Lua Pattern Matching
body: <p>I am trying to parse chemical formulas in Lua using simple pattern matching. However, I do not know how to specify a capture group as being optional. Here is the pattern I have come up with:</p>
  
  <pre class="lang-lua prettyprint-override"><code>pattern = "(%u%l*)(%d*)"
  </code></pre>
  
  <p>The first group captures the atomic symbol (i.e. "H", "He", etc..) and the second group captures the number of that atom in the molecule. This value is usually an integer value, but if it is 1, it is often omitted, such as in:</p>
  
  <pre class="lang-lua prettyprint-override"><code>formula = "C2H6O"
  </code></pre>
  
  <p>When I attempt to do a global match, if there is no match the result of <code>count</code> is <code>''</code> instead of what I would anticipate of <code>nil</code>. </p>
  
  <pre class="lang-lua prettyprint-override"><code>compound = {}
  for atom,count in string.gmatch(formula, pattern) do
      compound[atom] = count or 1
  end
  </code></pre>
  
  <p>Obviously I could just check if <code>count = ''</code>but I was curious if there was an optional capturing group in Lua.</p>