Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyparsing - zero or one from a group

How would I get zero or only one of each tokens out of a group of tokens? They can be in any order. Say this is my code:

def parseFunc(self, string):
    firstToken = CaselessKeyword("KeyWordOne")
    secondToken = CaselessKeyword("KeyWordTwo")
    thirdToken = CaselessKeyword("KeyWordThree")

    stmt = ZeroOrMore(firstToken | secondToken | thirdToken)
    return stmt.parseString(string)

With ZeroOrMore there's a problem since every token can show multiple times. With Optional they have to be in exact order they are listed.

This is my current solution:

stmt = ZeroOrMore(firstToken | secondToken | thirdToken)
tokens = stmt.parseString(string)
s = set()
for x in tokens:
    if x[0] in s: return "Error: redundant options"
    s.add(x[0])

return tokens
like image 554
Xitac Avatar asked Dec 10 '25 23:12

Xitac


1 Answers

Optional is the same as "zero or one":

stmt = Optional(firstToken | secondToken | thirdToken)

There is also a new multiplication form, similar to {min,max} in regex:

stmt = (firstToken | secondToken | thirdToken) * (0,1)

EDIT:

For arbitrary order, use Each (defined using operator &):

stmt = (Optional(firstToken) & Optional(secondToken) & Optional(thirdToken))
like image 188
PaulMcG Avatar answered Dec 12 '25 13:12

PaulMcG