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


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

regexps to objects

Started byandrea crotti <andrea.crotti.0@gmail.com>
First post2012-07-27 10:36 +0100
Last post2012-07-27 10:36 +0100
Articles 1 — 1 participant

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


Contents

  regexps to objects andrea crotti <andrea.crotti.0@gmail.com> - 2012-07-27 10:36 +0100

#26137 — regexps to objects

Fromandrea crotti <andrea.crotti.0@gmail.com>
Date2012-07-27 10:36 +0100
Subjectregexps to objects
Message-ID<mailman.2651.1343381802.4697.python-list@python.org>
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')

[toc] | [standalone]


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


csiph-web