Hostrange expansion
Peter Otten
__peter__ at web.de
Fri Sep 27 13:45:16 EDT 2013
Sam Giraffe wrote:
> I need some help in expanding a hostrange as in: h[1-100].domain.com
> should get expanded into a list containing h1.domain.com to
> h100.domain.com. Is there a library that can do this for me? I also need
> to valid the range before I expand it, i.e., h[1*100].domain.com should
> not be accept, or other formats should not be accepted.
To get you started:
import re
import itertools
def to_range(s, sep="-"):
"""
>>> to_range("9-11")
['9', '10', '11']
"""
lo, hi = s.split(sep)
return [str(i) for i in range(int(lo), int(hi)+1)]
def explode(s):
"""
>>> list(explode("h[3-5].com"))
['h3.com', 'h4.com', 'h5.com']
"""
parts = re.compile(r"(\[\d+-\d+\])").split(s)
parts[0::2] = [[p] for p in parts[0::2]]
parts[1::2] = [to_range(p[1:-1]) for p in parts[1::2]]
return ("".join(p) for p in itertools.product(*parts))
if __name__ == "__main__":
dom = "h[1-3]x[9-11].com"
print(dom)
for name in explode(dom):
print(" {}".format(name))
More information about the Python-list
mailing list