I want to define a special code block, which may starts by any combination of characters of {[<#
, and the end will be }]>#
.
Some example:
{
block-content
}
{##
block-content
##}
#[[<{###
block-content
###}>]]#
Is it possible with petitparser-dart?
Yes, back-references are possible, but it is not that straight-forward.
First we need a function that can reverse our delimiter. I came up with the following:
Then we have to declare the
stopDelimiter
parser. It is undefined at this point, but will be replaced with the real parser as soon as we know it.In the action of the
startDelimiter
we replace thestopDelimiter
with a dynamically created parser as follows:The rest is trivial, but depends on your exact requirements:
The code above defines the
blockContents
parser so that it reads through anything until the matchingstopDelimiter
is encountered. The provided examples pass:The above code doesn't work if you want to nest the parser. If necessary, that problem can be avoided by remembering the previous
stopDelimiter
and restoring it.