How can I parse a file containing a decimal numbers into a List<double>
in C# using ANTLR4? A complete, working example would illustrate how all the pieces go together.
The input file looks like this:
12.34
45.67
89.10
How can I parse a file containing a decimal numbers into a List<double>
in C# using ANTLR4? A complete, working example would illustrate how all the pieces go together.
The input file looks like this:
12.34
45.67
89.10
This is an updated version of an older answer to a different question, showing one way to do this task using C# and ANTRL4.
grammar Values;
parse : (number ( LINEBREAK | EOF ) )* ;
number : NUMBER ;
NUMBER : DIGIT '.' DIGIT ;
DIGIT : [0-9]+ ;
WS : [ \t] -> channel(HIDDEN) ;
LINEBREAK : '\r'? '\n' | '\r' ;
Now the class that implements the Listener pattern, now listening on number:
using System;
using System.Collections.Generic;
namespace ANTLR_File_To_Arrray
{
public class ValuesListener : ValuesBaseListener
{
public List<double> doubles = new List<double>();
public override void ExitNumber(ValuesParser.NumberContext context)
{
doubles.Add(Convert.ToDouble(context.GetChild(0).GetText()));
}
}
}
And finally the main program that reads the input file, sets up everything, walks the tree, and displays the accumulated double
values from the List<double>
exposed by the listener:
using System;
using System.IO;
using Antlr4.Runtime;
using Antlr4;
using Antlr4.Runtime.Tree;
namespace ANTLR_File_To_Arrray
{
class Program
{
static void Main(string[] args)
{
const string SOURCEFILE = @"D:\prj\ANTLR_File_To_Arrray\ANTLR_File_To_Arrray\source1.txt";
using (StreamReader fileStream = new StreamReader(SOURCEFILE))
{
AntlrInputStream inputStream = new AntlrInputStream(fileStream);
ValuesLexer lexer = new ValuesLexer(inputStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
ValuesParser parser = new ValuesParser(tokenStream);
ValuesParser.ParseContext context = parser.parse();
ValuesListener listener = new ValuesListener();
ParseTreeWalker walker = new ParseTreeWalker();
bool built = parser.BuildParseTree;
walker.Walk(listener, context);
foreach (double d in listener.doubles)
Console.WriteLine(d);
Console.ReadKey();
}
}
}
}