Assume I have the following PEG definition:
import pegs
let examplePeg = peg"""
A <- {L}? {D}?
L <- \a+
D <- \d+
"""
If I test strings against this PEG, I get:
if "abc" =~ examplePeg:
# `["abc", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]`
echo matches
if "123" =~ examplePeg:
# `["123", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]
echo matches
Now, since the subexpressions L and D are optional, it seems I need to look at the matched strings and check them again despite the PEG already defines whether I expect letters or digits for these subexpressions.
The only API I found that gives more control is eventParser, which on the other hand seems far too complicated for a relatively simple case as this.
Is there a simpler API (or a combination of them) in the pegs module, which I may have missed?
Afaik, stdlib peg is designed for nim compiler itself and somewhat limited. So, you may consider using npeg :
import npeg
let parser = peg("example"):
example <- >?word * >?number
word <- +Alpha
number <- +Digit
echo parser.match("abc").captures # @["abc", ""]
echo parser.match("123").captures # @["", "123"]
Thanks!
I had heard of npegs, but so far chose pegs because it's in the standard library and understands standard PEG syntax. That said, npeg's features are very impressive. :-)
Afaik, stdlib peg is designed for nim compiler itself and somewhat limited.
So I guess there's not much motivation to enhance this module? Probably it would be easier to implement a standard PEG parser with npegs as part of npegs than enhance the pegs module? ;-)