title: Java regex , matching variables in a math expression
body: <p>I have a string input that represents a formula like:</p>
  
  <pre><code>BMI = ( Weight / ( Height  * Height ) ) * 703
  </code></pre>
  
  <p>I want to be able to extract all legal variables into a <code>String[]</code></p>
  
  <p>Legal variables are determined with almost the same rules as Java variable naming convention, except only alphanumeric characters are allowed:</p>
  
  <ul>
  <li>Any alphabet character upper or lower, may be followed by a digit</li>
  <li>Any word/text</li>
  <li>Any word/text followed by a digit</li>
  </ul>
  
  <p>Therefore I expect the output to look like this:</p>
  
  <pre><code>BMI
  Weight
  Height
  </code></pre>
  
  <p><strong>This is my current attempt:</strong></p>
  
  <pre><code>/* helper method , find all variables in expression,
   * Variables are defined a alphabetical characters a to z, or any word , variables cannot have numbers at the beginning
   * using regex pattern "[A-Za-z0-9\\s]"
   */
  public static List&lt;String&gt; variablesArray (String expression)
  {
      List&lt;String&gt; varList = null; 
      StringBuilder sb = null; 
      if (expression!=null)
      {
          sb = new StringBuilder(); 
  
          //list that will contain encountered words,numbers, and white space
          varList = new ArrayList&lt;String&gt;();
  
          Pattern p = Pattern.compile("[A-Za-z0-9\\s]");
          Matcher m = p.matcher(expression);
  
          //while matches are found 
          while (m.find())
          {
              //add words/variables found in the expression 
              sb.append(m.group());
          }//end while 
  
          //split the expression based on white space 
          String [] splitExpression = sb.toString().split("\\s");
          for (int i=0; i&lt;splitExpression.length; i++)
          {
              varList.add(splitExpression[i]);
          }
      }
      return varList; 
  }
  </code></pre>
  
  <p>The result is not as I expected. I got extra empty lines, got "Height" twice, and shouldn't have gotten a number:</p>
  
  <pre><code>BMI
  
  
  Weight
  
  
  Height
  
  
  Height
  
  
  
  703
  </code></pre>