Skip to content

FAQ Frequently Asked Questions

Paul McGuire edited this page Jun 20, 2019 · 5 revisions

(in progress)

Is your question not here? Try searching for the pyparsing tag on StackOverflow, or requesting an addition to this page on the pyparsing subreddit

  1. Why do I only get the last value for a results name, when there are multiple matches?
  2. What is the difference between Or and MatchFirst?
  3. How do I evaluate the results from parsing infixNotation?

Why do I only get the last value for a results name, when there are multiple matches?

Results names by default use similar logic as Python dicts: if there are multiple values assigned for the same key, only the last assigned value is kept.

However, this behavior can be overridden, depending how the parser defines the results names.

If using the full expr.setResultsName("XYZ") form, add listAllMatches=True argument. This tells pyparsing to keep a list of all parsed values and return them as a list.

If using the short-cut expr("XYZ") form, add a '*' to the end of the name: expr("XYZ*"). This is equivalent to setting listAllMatches to True.

The trailing '*' is there in setResultsName for those cases where you use the short form of setResultsName: expr("name*") vs expr.setResultsName("name", listAllMatches=True). If you prefer calling setResultsName, then do not use the '*' notation, but instead pass the listAllMatches argument.

Short answer: Or evaluates all the alternatives and selects the longest match. MatchFirst evaluates the alternatives left-to-right and immediately returns when it finds the first match, even if a later alternative might be a better match. MatchFirst can result in faster parsers, and the issues with incorrectly selecting a shorter match can usually be addressed with careful order of the alternative selections, or in using expressions that do not overlap one another. More info on the Performance Tips page.

This will take a very long answer. For now, refer to SimpleBool.py in the examples for how to parse and evaluate infix of Boolean NOT, AND, and OR expressions; and eval_arith.py for 5-function arithmetic.