I want to parse a data file like this one (fictive example):
Name: bob
Age: 14
-----
Name: alice
-----
Let’s suppose, for this example, that the format of the file is complex enough that I don’t want to code it directly. I prefer using ANTLR to get a better parser.
Here is the question: how, with ANTLR, can I map this data to a structure, like a list ? I don’t need the complete grammar but only an explanation of how I can map data like that to a data struture.
I couldn’t find the answer that BA-S posted in a comment under your question, so I started writing a new answer. Without much explanation (read the other answer for more info), here is an example of how you could parse that simple input using ANTLR into a
List<Person>.The grammar describing your input:
The same grammar but then including embedded code:
And a small test class (with the
class Person):where
test.txtcontains:If you now run
Main, the following will be printed: