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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With