regexps to objects

andrea crotti andrea.crotti.0 at gmail.com
Fri Jul 27 11:36:34 CEST 2012


I have some complex input to parse (with regexps), and I would like to
create nice objects directy from them.
The re module doesn't of course try to conver to any type, so I was
playing around to see if it's worth do something as below, where I
assign a constructor to every regexp and build an object from the
result..

Do you think it makes sense in general or how do you cope with this problem?

import re
from time import strptime
TIME_FORMAT_INPUT = '%m/%d/%Y %H:%M:%S'

def time_string_to_obj(timestring):
    return strptime(timestring, TIME_FORMAT_INPUT)


REGEXPS = {
    'num': ('\d+', int),
    'date': ('[0-9/]+ [0-9:]+', time_string_to_obj),
}


def reg_to_obj(reg, st):
    reg, constr = reg
    found = re.match(reg, st)
    return constr(found.group())


if __name__ == '__main__':
    print reg_to_obj(REGEXPS['num'], '100')
    print reg_to_obj(REGEXPS['date'], '07/24/2012 06:23:13')



More information about the Python-list mailing list