1

I have a long list of numberseries formated like this:

["4450[0-9]", "6148[0-9][0-9]"]

I want to make a list from one of those series with single numbers:

[44500,44501,..., 44509]

i need to do this for many series within the original list and i'm wondering what the best way is for doing that?

sousys
  • 51
  • 6
  • I'm hoping there is some python module that does this instead of me diving deep into regexp or whatnot – sousys Sep 15 '16 at 17:42

3 Answers3

2

Probably not the best solution, but you can approach it recursively looking for the [x-y] ranges and generating values (using yield and yield from in this case, hence for Python 3.3+):

import re

pattern = re.compile(r"\[(\d+)-(\d+)\]")

def get_range(s):
    matches = pattern.search(s)
    if not matches:
        yield int(s)
    else:
        start, end = matches.groups()
        for i in range(int(start), int(end) + 1):
            repl = pattern.sub(str(i), s, 1)
            yield from get_range(repl)


for item in get_range("6148[0-9][0-9]"):
    print(item)

Prints:

614800
614801
...
614898
614899
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1
def invertRE(x):
    if not x:
        yield []
    else:
       idx = 1 if not x.startswith("[") else x.index("]") + 1
       for rest in invertRE(x[idx:]):
           if x.startswith("["):
               v1,v2 = map(int,x[1:idx-1].split("-"))
               for i in range(v1,v2+1):
                  yield [str(i),]+rest
           else:
               yield [x[0],] + rest

print(map("".join,invertRE("123[4-7][7-8]")))

Im pretty sure this will work ... but really you should try something on your own before comming here ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Found this module which seems to do what i want.

https://pypi.python.org/pypi/braceexpand/0.1.1

>>> from braceexpand import braceexpand
>>> s = "1[0-2]"
>>> ss = "1[0-2][0-9]"
>>> list(braceexpand(s.replace("[", "{").replace("-","..").replace("]","}")))
['10', '11', '12']
>>> list(braceexpand(ss.replace("[", "{").replace("-","..").replace("]","}")))
['100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129']

alecxe's answer is still the "best" answer and not a shortcut tho

sousys
  • 51
  • 6