need simple parsing ability

Christopher T King squirrel at WPI.EDU
Fri Jul 16 15:37:43 EDT 2004


On Fri, 16 Jul 2004, george young wrote:

> Mmm, not quite.  If ns=='foo08-11', your fs==[foo8, foo9, foo10, foo11] 
> which is wrong.  It should yield  fs==[foo08, foo09, foo10, foo11].
> I.e., it must maintain leading zeros in ranges.

An updated version of what I previously posted should do the trick:

---

import re

def expand(pattern):
    r = re.search('\d+-\d+$',pattern)
    if r is None:
        yield pattern
        return
    s,e = r.group().split('-')
    l = len(s)
    for n in xrange(int(s),int(e)+1):
        yield pattern[:r.start()]+'%0*d' % (l,n)

def expand_list(pattern_list):
    return [ w for pattern in re.split('\s*,\s*',pattern_list)
             for w in expand(pattern) ]

pattern_list = '9,foo07-11,2-4,xxx'

print expand_list(pattern_list)

# --> ['9', 'foo07', 'foo08', 'foo09', 'foo10', 'foo11', '2', '3', '4', 'xxx']

---

Why do I feel like there's a contest going? ;)




More information about the Python-list mailing list