def t_FUNC_(self, t):
r'(?i)I|(?i)J|(?i)K|(?i)L|(?i)M|(?i)N|(?i)Y'
return t
In above function I'm returning a regex which means FUNC can be I or J or K or L or M or N or Y.
Now, i have a dictionary like :
dic = { 'k1':'v1', 'k2':'v2' }
I have an access to this dictionary in the above function. How do i dynamically generate the regex from the keys of the dictionary. Size of the dictionary is also not fixed.
So, i want to replace r'(?i)I|(?i)J|(?i)K|(?i)L|(?i)M|(?i)N|(?i)Y'
with something like r'(?i)k1|(?i)k2
.
PS: Above pattern code is used to generate tokens when we write our lexer using ply library in python.
To put the keys of the dict into your regex is as simple as:
regex = '|'.join('(?i){}'.format(k) for k in data)
data = {'k1': 'v1', 'k2': 'v2'}
regex = '|'.join('(?i){}'.format(k) for k in data)
print(regex)
(?i)k1|(?i)k2
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