title: Distinguish Optional Tokens While Visiting an Antlr Rule
body: <p>This question is about how to distinguish optional tokens while visiting an antlr rule.</p>
  
  <p>I have a parser rule I have defined in an antlr4 grammar called 'assign' which attempts to assign the result of an expression to a tag represented by an INT, for example 215="FOO".  It also allows assignment to a tag <em>index</em>, for example 215[2] = "FOO".  My question is how can I distinguish INTs of the form 215 vs. the form 215[2] by looking at the objects provided by antlr during the evaluation of the assign rule?</p>
  
  <pre><code>assign  : INT '=' expr  ;
  INT     : '-'? DIGIT+ ('[' DIGIT+ ']')?;
  DIGIT   :  [0-9] ;
  </code></pre>
  
  <p>I have defined a visitor method to capture the parser's evaluation of the "assign" rule for a token stream: </p>
  
  <p>215[2]="FOO"</p>
  
  <pre><code>@Override
  public String visitAssign(@NotNull FixRulesParser.AssignContext ctx) {
  String left = ctx.getStart().getText();
  String right = ctx.getStop().getText();
  ...
  </code></pre>
  
  <p>At this point left = "215[2]" and right = "FOO"</p>
  
  <p>Does the ctx object offer a way to determine if the left side of the assignment (215[2]) actually contains the optional '[2]' defined by INT?  I want to distinguish INTs of the form 215[2] vs. 215.  I use a Java regex to parse 'left' (see below) to make the determination but I'm wondering if I can get the answer directly from antlr.</p>
  
  <pre><code>Pattern p = Pattern.compile("(-?\\d+)((\\[)(\\d+)(\\]))?");
  </code></pre>