python - How to define grammar for minimum 1 of foo and maximum 1 of bar - Stack Overflow

时间: 2025-01-06 admin 业界

In parsimonious, I'm trying to define a grammar where there has to be one occurrence of foo and zero to 1 occurrence of bar and in any order. How do I get parsimonious to throw an error ?

from parsimonious.grammar import Grammar

g = Grammar(r"""
    text = ws* "section" ws* (foo / bar)+ ws*  
    foo = ws* "foo" ws*
    bar = ws* "bar" ws*
    ws = ~"\s*"
""")

print(g.parse("""section foo""")) 
print(g.parse("""section foo bar bar"""))  # How to throw error as more than one bar
print(g.parse("""section bar""")) # How to throw error as foo is required
print(g.parse("""section bar foo"""))  
print(g.parse("""section foo bar"""))  

In parsimonious, I'm trying to define a grammar where there has to be one occurrence of foo and zero to 1 occurrence of bar and in any order. How do I get parsimonious to throw an error ?

from parsimonious.grammar import Grammar

g = Grammar(r"""
    text = ws* "section" ws* (foo / bar)+ ws*  
    foo = ws* "foo" ws*
    bar = ws* "bar" ws*
    ws = ~"\s*"
""")

print(g.parse("""section foo""")) 
print(g.parse("""section foo bar bar"""))  # How to throw error as more than one bar
print(g.parse("""section bar""")) # How to throw error as foo is required
print(g.parse("""section bar foo"""))  
print(g.parse("""section foo bar"""))  
Share Improve this question asked Dec 16, 2024 at 2:35 hm-distrohm-distro 112 bronze badges 1
  • Probably easier to just enumerate the possibilities, foo, foo bar, or bar foo. (Or should that be "at least one" occurrence of foo, matching the title?) – chepner Commented Dec 16, 2024 at 14:01
Add a comment  | 

1 Answer 1

Reset to default 0

Your grammar isn't correct.

You are looking for

text = ws* "section" ws* foo*  bar foo* ws*