title: C# parse chemical formula WITH PARENTHESES
body: <p>I'm trying to write a C# chemical formula parser that extracts a chemical formula from a string input. I have figured out how to do this with chemical formulas that don't contain parentheses, such as H2O, etc. However, I have no clue how to make this work with parentheses, such as with a formula like Al2(HPO4)3.</p>
  
  <p>Just a note, but this would output a list of classes known as "<em>FormulaComponents</em>" that have two variables, an Element (string), and a number.</p>
  
  <p>Any ideas?</p>
  
  <p>EDIT: Here's my current attempt. It handles everything short of parentheses.</p>
  
  <pre><code>public static Formula Parse(string input)
  {
      var components = new List&lt;FormulaComponent&gt;();
  
      const string elementRegex = "([A-Z][a-z]*)([0-9]*)";
      const string validateRegex = "^(" + elementRegex + ")+$";
  
      if (!Regex.IsMatch(input, validateRegex))
          throw new FormatException("Input string was in an incorrect format.");
  
      foreach (Match match in Regex.Matches(input, elementRegex))
      {
          var name = match.Groups[1].Value;
  
          var count = match.Groups[2].Value != "" ?
              int.Parse(match.Groups[2].Value) :
              1;
  
          if (ElementManager.FindElementBySymbol(name) == null)
              throw new FormatException(name + " is not recognized as a valid element symbol.");
  
          components.Add(new FormulaComponent { Element = ElementManager.FindElementBySymbol(name), Quantity = count });
      }
  
      return new Formula { Components = components };
  }
  </code></pre>