regex - How can I implement grouping preference in antlr? -


i want write lexer , parser take expressions like

(4+y)*8 4+5*x (3)+(z*(4+w))*6 

and parse them considering priority of multiplication on addition. in particular, can't figure out how avoid

4+5*x 

being grouped as

multiplication(addition(4,5),5) instead of addition(4+multiplication) 

my lexer looks that:

plus     : '+'; times    : '*'; number   : [0-9]+'.'?[0-9]*; variable : [(a-z)|(a-z)]+; opening  : '('; closing  : ')'; whitespace : [ \t\r\n]+ -> skip ; 

the correct grouping happen automatically if define lower-priority operations closer "root expression" rule higher-priority ones:

expr :       e=multdivexpr     (   plus e=multdivexpr     |   minus e=multdivexpr     )* ;  multdivexpr :       e=atomexpr      (   times e=atom     |   div e=atom     |   rem e=atom     )* ;   atom :       number     |   variable     |   opening e=expr closing ; 

a simple way understand what's going on think recursive descent parser generated antlr use multdivexpr non-terminals "building blocks" "additive" expr non-terminal, therefore applying grouping multiplication , division before considering addition , subtraction.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -