Parsing a phrase with Sprache(Words seperated by spaces)

910 Views Asked by At

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.

1

There are 1 best solutions below

0
Heinrich Walkenshaw On

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