If you are using Maven in your project you have to add this to your “dependencies” section: org.antlr antlr4-runtime 4.7 Implementation 'org.antlr:antlr4-runtime:4.7' with Android Studio you have to add this line to the “dependencies” section of your app’s adle: To use this code you also need the ANTLR Runtime in your project. String name = parser.main().name().getText() Īnd the variable “name” would contain the parsed name “John”. TestParser parser = new TestParser(new CommonTokenStream(lexer))
TestLexer lexer = new TestLexer(omString("Hallo John!")) Val parser = TestParser(CommonTokenStream(lexer)) Val lexer = TestLexer(omString("Hallo John!")) Now you could write the following code in Kotlin Then click on “Generate ANTLR Recognizer”: Right click your “Test.g4” file and select “Configure ANTLR”.Įnter the root path where your project’s sources are saved and the package name that the parser should use. Now let’s see how we can access the data from Java/Kotlin. If you enter an invalid text it will show an error. On the right side you should see the parsed result:Īs you can see, it has correctly parsed the name into a separate tag. Now type “Hello John!” into the text area of the ANTLR Preview pane. To fix this, right click on “main” in the “Test.g4” file and select “Test Rule main”: Write the following lines into the file:Ī new pane should appear that should display “text.g4 start rule: ”. Now create an empty file and name it “Test.g4”. Open the preferences and select “Plugins > Browse repositories”: Afterward you can extend the example or write your own files to parse more complex input.įirst you need to install the ANTLR plugin.
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.