antlr4 grammar non greedy
<p>I'm trying to write a grammar the allows me to write any expression in a if statement. </p>

<p>My if statement will be something like below:
if [ x == 1 ] [Do some stuff]</p>

<p>The expression is supposed to be any Python expression. </p>

<p>If I use the non-greedy match like below, how can I specify '[' or ']' as a part of expression? List comprehension will be problem with my grammar. </p>

<pre><code>ifval
  : (SPACE)* IF (SPACE|WORD)* SQRLBRACE .*? SQRRBRACE (WORD|SPACE)* &lt;blah&gt; &lt;blah&gt;;

WORD     : ('a'..'z' | 'A'..'Z'| '_' | '-')+;
NUM      : [0-9];
NEWLINE  : '\r'? '\n' | '\r';
SPACE    : (' ' | '\t') ;
SQRRBRACE: ']';
SQRLBRACE: '[';
</code></pre>

<p>Generalized, use a typical statement formulation:</p>

<pre><code>stmt   : ifval
       | ....
       ;

ifval  : IF expr body ;

expr   : LBRACK expr? RBRACK
       | NOT expr 
       | WORD ( LBRACK WORD? RBRACK )? // value or array[idx]
       | ....
       ;

body   : WORD
       | LBRACE stmt* RBRACE
       | .... 
       ;
</code></pre>

<p>The <code>expr</code> rule will handle the occurrence of optional and nested brackets through recursion.</p>

<p>BTW, almost always better to hide whitespace in the grammar, even for Python/whitespace sensitive languages. By hiding, the WS remains easily accessible for computing indentation level. And, the grammar is not then polluted by having to specify every conceivable location of SPACE*.</p>

python antlr4