O'Reilly logo

The Definitive ANTLR 4 Reference, 2nd Edition by Terence Parr

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Executing ANTLR and Testing Recognizers

Here’s a simple grammar that recognizes phrases like hello parrt and hello world:

install/Hello.g4
 
grammar​ Hello; ​// Define a grammar called Hello
 
r : ​'hello'​ ID ; ​// match keyword hello followed by an identifier
 
ID : [a-z]+ ; ​// match lower-case identifiers
 
WS : [ \t\r\n]+ -> skip ; ​// skip spaces, tabs, newlines, \r (Windows)

To keep things tidy, let’s put grammar file Hello.g4 in its own directory, such as /tmp/test. Then we can run ANTLR on it and compile the results.

 
$ ​cd /tmp/test
 
$ ​# copy-n-paste Hello.g4 or download the file into /tmp/test
 
$ ​antlr4 Hello.g4 ​​# Generate parser and lexer using antlr4 alias from before
 
$ ​ls
 
Hello.g4 HelloLexer.java HelloParser.java ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required