0

Imagine a small PEG grammar like

from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

grammar = Grammar(
    r"""
    term    = lpar (number comma? ws?)+ rpar
    number  = ~"\d+"
    lpar    = "("
    rpar    = ")"
    comma   = ","
    ws      = ~"\s*"
    """
)

tree = grammar.parse("(5, 4, 3)")
print(tree)

Which outputs

<Node called "term" matching "(5, 4, 3)">
    <Node called "lpar" matching "(">
    <Node matching "5, 4, 3">
        <Node matching "5, ">
            <RegexNode called "number" matching "5">
            <Node matching ",">
                <Node called "comma" matching ",">
            <Node matching " ">
                <RegexNode called "ws" matching " ">
        <Node matching "4, ">
            <RegexNode called "number" matching "4">
            <Node matching ",">
                <Node called "comma" matching ",">
            <Node matching " ">
                <RegexNode called "ws" matching " ">
        <Node matching "3">
            <RegexNode called "number" matching "3">
            <Node matching "">
            <Node matching "">
                <RegexNode called "ws" matching "">
    <Node called "rpar" matching ")">

How to get the number regex part from term in this example? I know I could use a NodeVisitor class and examine each number but I would like to get the regex part from within term.

Jan
  • 42,290
  • 8
  • 54
  • 79

1 Answers1

1

It's probably better to use the NodeVisitor class and walk the tree that way, but here's another simple solution:

from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

grammar = Grammar(
    r"""
    term    = lpar (number comma? ws?)+ rpar
    number  = ~"\d+"
    lpar    = "("
    rpar    = ")"
    comma   = ","
    ws      = ~"\s*"
    """
)

tree = grammar.parse("(5, 4, 3)")

def walk(node):
    if node.expr_name == 'number':
        print(node)
    for child in node.children:
        walk(child)

walk(tree)

# <RegexNode called "number" matching "5">
# <RegexNode called "number" matching "4">
# <RegexNode called "number" matching "3">
Josh Voigts
  • 4,114
  • 1
  • 18
  • 43