Parse and return a list of doubles using ANTLR4

2019-05-30 07:24发布

问题:

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

回答1:

This is an updated version of an older answer to a different question, showing one way to do this task using C# and ANTRL4.

The Grammar

grammar Values;
parse : (number ( LINEBREAK | EOF ) )* ;
number : NUMBER ;
NUMBER : DIGIT '.' DIGIT ;
DIGIT : [0-9]+ ;
WS : [ \t] -> channel(HIDDEN) ;
LINEBREAK :  '\r'? '\n' | '\r' ;

The Listener

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()));
        }
    }
}

Main Program

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();
            }
        }
    }
}


标签: c# antlr antlr4