简体   繁体   中英

parsing lines of text ending with '\n' using sprache

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

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");

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM