Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #54902 > unrolled thread

Re: Hostrange expansion

Started byPeter Otten <__peter__@web.de>
First post2013-09-27 19:45 +0200
Last post2013-09-27 19:45 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Hostrange expansion Peter Otten <__peter__@web.de> - 2013-09-27 19:45 +0200

#54902 — Re: Hostrange expansion

FromPeter Otten <__peter__@web.de>
Date2013-09-27 19:45 +0200
SubjectRe: Hostrange expansion
Message-ID<mailman.388.1380303869.18130.python-list@python.org>
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))

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web