pyparsing / pyparsing

Python library for creating PEG parsers
MIT License
2.15k stars 276 forks source link

How to resolve the conflict between OneOrMore and Keyword #558

Closed Gu-f closed 1 month ago

Gu-f commented 1 month ago
import pyparsing as pp

str_text = "get a b c from cup;"

content = pp.Word(pp.alphas)

content_pos = pp.OneOrMore(content).set_name("contents")

container = pp.Word(pp.alphas).set_name("container")
end_flag = ';'

get = pp.Keyword('get')
from_ = pp.Keyword('from')

pattern = get + content_pos + from_ + container + end_flag

print(pattern.parse_string(str_text))

I got an error pyparsing.exceptions.ParseException: Expected Keyword 'from', found ';' (at char 18), (line:1, col:19) from is matched by content_pos
But I want from as a keyword to be matched by from_
How should I fix it, thanks

Gu-f commented 1 month ago

I found the stop_on, it satisfies. content_pos = pp.OneOrMore(content, stop_on=from_).set_name("contents")

ptmcg commented 1 month ago

Glad you were able to find this solution for yourself - stop_on is definitely the correct solution for this.

There is a note in the wiki on Common Pitfalls when Writing Parsers, and I also just wrote up a blog post that goes into more detail on just what is going on in pyparsing.

Also, I saw that stop_on did not correctly represent its negative lookahead element in the railroad diagrams, so this will be fixed in the next release.