In this example we will parse a simple text with ANTLR to see how to set up and use ANTLR with Intellij IDEA or Android Studio. Afterward you can extend the example or write your own files to parse more complex input. First you need to install the ANTLR plugin. Open the preferences and select … Continue reading “Creating and Testing an ANTLR parser with Intellij IDEA or Android Studio”
In this example we will parse a simple text with ANTLR to see how to set up and use ANTLR with Intellij IDEA or Android Studio. Afterward you can extend the example or write your own files to parse more complex input.
First you need to install the ANTLR plugin. Open the preferences and select “Plugins > Browse repositories”:
Then select the ANTLR plugin:
Now create an empty file and name it “Test.g4”. Write the following lines into the file:
main: 'Hello ' name '!';
Then click on ANTLR Preview:
A new pane should appear that should display “text.g4 start rule: <select from navigator or grammar>”. To fix this, right click on “main” in the “Test.g4” file and select “Test Rule main”:
Now type “Hello John!” into the text area of the ANTLR Preview pane. On the right side you should see the parsed result:
As you can see, it has correctly parsed the name into a separate tag. If you enter an invalid text it will show an error.
Now let’s see how we can access the data from Java/Kotlin. Right click your “Test.g4” file and select “Configure ANTLR”.
Enter the root path where your project’s sources are saved and the package name that the parser should use. And specify “Java” as language:
Then click on “Generate ANTLR Recognizer”:
Now you could write the following code in Kotlin
val lexer = TestLexer(CharStreams.fromString("Hallo John!"))
val parser = TestParser(CommonTokenStream(lexer))
val name = parser.main().name().text
or in Java
TestLexer lexer = new TestLexer(CharStreams.fromString("Hallo John!"));
TestParser parser = new TestParser(new CommonTokenStream(lexer));
String name = parser.main().name().getText();
and the variable “name” would contain the parsed name “John”.
To use this code you also need the ANTLR Runtime in your project. If you are using Gradle e.g. with Android Studio you have to add this line to the “dependencies” section of your app’s build.gradle:
If you are using Maven in your project you have to add this to your “dependencies” section:
Too see which rules you can use in the g4 file you can use the documentation here: