Expanding Regex In Python
My program takes in a regex for describing a set of devices. For example, --device=dev{01,02}{nyc}.hukka.com should expand to dev01nyc.hukka.com and dev02nyc.hukka.com How can I
Solution 1:
If we re.split on the braces, we get:
In [7]: re.split(r'\{(.*?)\}',userstring)
Out[7]: ['--device=dev', '01,02', '', 'nyc', '.hukka.com']
Every other item in the list came from inside braces, which we next need to split on commas:
In [8]: [ part.split(',') if i%2else [part] for i,part inenumerate(re.split(r'\{(.*?)\}',userstring)) ]
Out[8]: [['--device=dev'], ['01', '02'], [''], ['nyc'], ['.hukka.com']]
Now we can use itertools.product to enumerate the possibilities:
import re
import itertools
userstring = '--device=dev{01,02}{nyc}.hukka.com'for x in itertools.product(*[ part.split(',') if i%2else [part] for i,part inenumerate(re.split(r'\{(.*?)\}',userstring)) ]):
print(''.join(x))
yields
--device=dev01nyc.hukka.com
--device=dev02nyc.hukka.com
Solution 2:
Simply by extract the first braces to a group and iterate over this group :
import re
user_arg = "dev{01,02}{nyc}.hukka.com"
regex = re.compile('dev{(?P<dev_id>[^}]*)}{(nyc)}.hukka.com')
result = regex.search(user_arg)
devices = []
for dev_id in result.group(1).split(',') :
devices.append("dev%s%s.hukka.com" % (dev_id, result.group(2)))
print devices
That returns :
$ ['dev01nyc.hukka.com', 'dev02nyc.hukka.com']
Post a Comment for "Expanding Regex In Python"