0

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

umbersar
  • 1,821
  • 3
  • 24
  • 34
  • It looks like the Parser `Text` already treats the '\n' symbol like the end of the line, so by the time newLine gets there, there is (unexpectedly) no text to parse. If you want to do this, you should probably use a different character for EOLs. Replacing '\n' with something like '!' in your code will run as expected. – dmedine Dec 06 '22 at 06:15
  • Could be that the "Parse" use a variable of length, does the trim itself and expects the final string to be 8 long, while after the trim it will be only 7. Could also be that it reads the string as literal as posible and expects a final string that is 8 long but recieves something that equals 9 long... idk. I wouldn't use .Trim() like Oleg suggests, but i would try using .Split('\n'), here you will know exactly when the new line is needed to be inserted after the fact. – RatzMouze Dec 06 '22 at 06:23

2 Answers2

1

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");
asgerhallas
  • 16,890
  • 6
  • 50
  • 68
0

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;

Oleg_B
  • 34
  • 1
  • 1
  • 7