Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically generate regex from the keys of the dictionary python

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.

like image 235
zubug55 Avatar asked Sep 08 '25 09:09

zubug55


1 Answers

To put the keys of the dict into your regex is as simple as:

Code:

regex = '|'.join('(?i){}'.format(k) for k in data)

Test Code:

data = {'k1': 'v1', 'k2': 'v2'}
regex = '|'.join('(?i){}'.format(k) for k in data)
print(regex)

Results:

(?i)k1|(?i)k2
like image 193
Stephen Rauch Avatar answered Sep 10 '25 02:09

Stephen Rauch