Capture data using Code Block Captures
masterCode block captures allow you to execute embedded Nim code when a rule matches. This is done by ending a rule with a colon : followed by an indented block of Nim code.
Accessing Captured Data
Inside the code block, you can access captured strings via the capture[] sequence of type seq[Capture].
capture[0]is the total subject matched by the rule.capture[1],capture[2], etc., correspond to explicit>string captures made by the rule or its children.
Syntactic Sugar
To simplify access, NPeg provides shorthand variables:
$0to$9: Rewritten tocapture[n].s(the captured string).@0to@9: Rewritten tocapture[n].si(the integer index/offset in the subject).
Note: Code blocks are executed during parsing, even if the match is later invalidated by backtracking. Code block captures also consume all embedded string captures, making them unavailable in the final MatchData.captures list.
Pushing new captures
You can manually add new captures to the result by calling push(s: string) within the code block (experimental feature).
let p = peg foo:
foo <- >(1 * >1) * 1:
echo "$0 = ", $0
echo "$1 = ", $1
echo "$2 = ", $2
echo p.match("abc").ok
# Output:
# $0 = abc
# $1 = ab
# $2 = b