简体   繁体   中英

Parsing a phrase with Sprache(Words seperated by spaces)

I'm attempting to write a parser in Sprache that will parse a phrase

The basic rule is that it should include words seperated by a single space, with both the first and last character of the string being a space.

I would expect to call something like the following:

string phrase = PhraseParser.Parse("         I want to return up to this point        ");

And have the resulting string be "I want to return up to this point".

I have tried numerous implementations with none quite doing it for me.

Update Thanks to @PanagiotisKanavos, the trick would be to use the .Then() operator. The following words:

public static Parser<string> WordParser =
        Parse.Letter.Many().Text().Token();

public static Parser<string> PhraseParser =
        from leading in Parse.LetterOrDigit.Many().Text()
        from rest in Parse.Char(' ').Then(_ => WordParser).Many()
        select leading + " " + String.Join(" ", rest);

Can probably still clean it up a bit, but the concept is there.

Thanks to @PanagiotisKanavos, the trick would be to use the .Then() operator. The following works:

public static Parser<string> WordParser =
    Parse.Letter.Many().Text().Token();

public static Parser<string> PhraseParser =
    from leading in Parse.LetterOrDigit.Many().Text()
    from rest in Parse.Char(' ').Then(_ => WordParser).Many()
    select leading + " " + String.Join(" ", rest);

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