title: Why do I have empty tokens in Java String.split(regex)?
body: <p>I'm new to regular expression, I'm trying to use it to parse tokens separated by "(", ")" and blank space. This is my attempt:</p>
  
  <pre><code>String str = "(test (_bit1 _bit2 |bit3::&amp;92;test#4|))";
  String[] tokens = str.split("[\\s*[()]]"); 
  for(int i = 0; i &lt; tokens.length; i++)
    System.out.println(i + " : " + tokens[i]);
  </code></pre>
  
  <p>I expect the following output:</p>
  
  <blockquote>
    <p>0 : test<br>
      1 : _bit1<br>
      2 : _bit2<br>
      3 : |bit3::&amp;92;test#4|</p>
  </blockquote>
  
  <p>However, there are two empty tokens appear in the actual output:</p>
  
  <blockquote>
    <p>0 :<br>
      1 : test<br>
      2 :<br>
      3 : _bit1<br>
      4 : _bit2<br>
      5 : |bit3::&amp;92;test#4|  </p>
  </blockquote>
  
  <p>I don't understand why I have two empty tokens in position 0 and 2. Could anyone give me a hint? Thank you.</p>
  
  <p>===== Update ====</p>
  
  <p>There was an answer of <a href="https://stackoverflow.com/users/20938/alan-moore">Alan Moore</a> who deleted it. But I like the answer, so I copy it here for my own reference.</p>
  
  <blockquote>
    <p>Your regex, [\s*[()]], matches one whitespace character (\s) or one of
    the characters *, (, or ). The delimiter at the beginning of the
    string (() is why you get the empty first token. There's no way around
    that; you just have to check for an empty first token and ignore it.</p>
    
    <p>The second empty token is between the first space and the ( that
    follows it. That one's on you, because you used * (zero or more)
    instead of + (one or more). But fixing it isn't that simple. You want
    to split on spaces, parens, or both, but you have to make sure there's
    at least one character, whichever it is. This might do it:</p>
    
    <p>\s*[()]+\s*|\s+</p>
    
    <p>But you probably should allow for spaces between parens, too:</p>
    
    <p>\s*(?:[()]+\s*)+|\s+</p>
    
    <p>As a Java string literal, that would be:</p>
    
    <p>\s*(?:[()]+\s*)+|\s+</p>
  </blockquote>