title: How to match optional open/close tags in JavaCC?
body: <p><strong>What JavaCC syntax does implement grammar that can parse these kind of lines:</strong></p>
  
  <pre><code>[b]content[/b]
  content[/b]
  [b]content
  </code></pre>
  
  <p>Although the JavaCC parser needs to parse all lines, it <em>must distinguish correct and incorrect tagging</em> behavior.</p>
  
  <p><strong>Correct tags</strong> are like the 1st line, they have an open and close tag. When the tags are matched this will output a bold formated text.</p>
  
  <p><strong>Incorrect tags</strong> are like line's 2 and 3, they have no matching open or close tag. When these occure, they are written to the output as-is and will not be interpreted as tags.</p>
  
  <p>I have tried the JavaCC code below (LOOKAHEAD = 999999). Problem is, this syntax will <em>always match everything as invalidTag()</em> instead of <em>bold()</em>. How can I make sure that the JavaCC parser will match <em>bold()</em> when ever possible?</p>
  
  <pre><code>String parse() :
  {}
  {
      body() &lt;EOF&gt;
      { return buffer; }
  }
  
  void body() :
  {}
  {
      (content())*
  }
  
  void content() :
  {}
  { 
      (text()|bold()|invalidTag)
  }
  
  void bold() :
  {}
  {
      { buffer += "&lt;b&gt;";  }
      &lt;BOLDSTART&gt;(content())*&lt;BOLDEND&gt;
      { buffer += "&lt;/b&gt;"; }
  }
  
  void invalidTag() :
  {
  }
  {
      &lt;BOLDSTART&gt; | &lt;BOLDEND&gt;
      { // todo: just output token
      }
  }
  
  TOKEN :
  {
      &lt;TEXT : (&lt;LETTER&gt;|&lt;DIGIT&gt;|&lt;PUNCT&gt;|&lt;OTHER&gt;)+ &gt;
      |&lt;BOLDSTART : "[b]" &gt;
      |&lt;BOLDEND : "[/b]" &gt;
  
      |&lt;LETTER : ["a"-"z","A"-"Z"] &gt;
      |&lt;DIGIT : ["0"-"9"] &gt;
      |&lt;PUNCT : [".", ":", ",", ";", "\t", "!", "?", " "] &gt;
      |&lt;OTHER : ["*", "'", "$", "|", "+", "(", ")", "{", "}", "/", "%", "_", "-", "\"", "#", "&lt;", "&gt;", "=", "&amp;", "\\"]     &gt;
  }
  </code></pre>