Home > other >  parsing lines of text ending with '\n' using sprache
parsing lines of text ending with '\n' using sprache

Time:12-06

I have a sample text line, "FunTest\n", that I am trying to parse with sprache. I have written some sample code, see below, but it fails with an exception:

Parsing failure: Unexpected end of input reached; expected (Line 2, Column 1); recently consumed: FunTest

using Sprache;
void Main()
{
    Parser<char> NEW_LINE_Parser = Parse.Char('\n').Token();

    Parser<string> Text =
           (from content in Parse.CharExcept('\n').Many().Text()
            select content).Token();

    Parser<string> Text_Parser =
                from commandStr in Text
                from newLine in NEW_LINE_Parser
                select commandStr;

    Text_Parser.Parse("FunTest\n");
}

Why is it failing with an error? I want to extract match the text before '\n' character

CodePudding user response:

It's .Token() that eats the newline char. I would say you don't need it, as you parse any char except the newline - so whitespace is parsed too, and returned.

If you like the command string trimmed, you could trim it in Text_Parser, like:

Parser<char> NEW_LINE_Parser = Parse.Char('\n');

Parser<string> Text =
    (from content in Parse.CharExcept('\n').Many().Text()
        select content);

Parser<string> Text_Parser =
    from commandStr in Text
    from newLine in NEW_LINE_Parser
    select commandStr.Trim();

Text_Parser.Parse("FunTest \n");

CodePudding user response:

Isn't it easier to use Text_Parser.trim();? This one cuts out the end spaces, tabulators and \n. Also Include (if it isn't included) using System;

  • Related