Parse string between a pair of delimiters (that are strings)

169 views Asked by At

I would like to create a parser using Superpower to match strings like:

<<This is my text>>

That is, a string delimited by a pair of strings (left and right). In this case, the delimiting strings are << and >>.

For now, all I've got is a parser that only works when delimiters are single chars:

public static TextParser<TextSpan> SpanBetween(char left, char right)
{
    return Span
        .MatchedBy(Character.Except(right).Many())
        Between(Character.EqualTo(left), Character.EqualTo(right));
}

How should I modify it with left and right being strings instead?

1

There are 1 answers

0
Andrew Savinykh On
public static TextParser<TextSpan> SpanBetween(string left, string right)
{
    return Span
        .MatchedBy(Parse.Not(Span.EqualTo(right)).Then(p => Character.AnyChar).Many())
        .Between(Span.EqualTo(left), Span.EqualTo(right));
}

or with Span.Except

public static TextParser<TextSpan> SpanBetween(string left, string right)
{
    return Span
        .MatchedBy(Span.Except(right))
        .Between(Span.EqualTo(left), Span.EqualTo(right));
}

I'm assuming, contrary to what your questions says that you want to match text between the delimiters, not the entire string, since this is what your example shows.