Is there a nice way in Python to do:
- Check a String matches a set of regular expressions
- If yes: get the matching parts back as tuples.
So essentially I want a simple way to enter simple parser/scanner grammars, and simply extract all matching in a certain structure (e.g. tuples)
So suppose we have encoded in a String a country code, an city name and an index. We want to extract this:
input = "123-NEWYORK-[2]"
grammar = "<country,[0-9]+>-<city,[A-Z]*>-[<index,[0-9]*>"
res = HOW_TO_DO_THIS(input,grammar)
if res is None:
print("Does not match")
else
(countrycode,city,index) = res
With python3 you can do, note that the regex has been modified:
Modifications:
re.findall(patter, input_string)
. Not the opposite.if not x
is easier (and more generic) thanif x is None