Skip to content

Instantly share code, notes, and snippets.

@lopezezequiel lopezezequiel/example.py
Last active Dec 28, 2015

Embed
What would you like to do?
recomp lets you build regular expressions easily and reuse them
from recomp import recomp
import re
#definition
r = recomp()
r.year = '[0-9]{2}'
r.month = '(?:0[1-9]|1[12])'
r.day = '(?:0[1-9]|[12][0-9]|3[01])'
r.date = '{day}\-{month}\-{year}'
r.hh = '(?:[01][0-9]|2[0-3])'
r.mm = '(?:[0-5][0-9])'
r.ss = '{mm}'
r.time = '{hh}\:{mm}\:{ss}'
r.datetime = '{date} {time}'
#print them
print r.mm
print r.date
print r.time
print r.datetime
#using re
print re.match(r.datetime, '27-12-15 21:08:15').group(0)
#redefine
r.year = '[0-9]{4}'
print re.match(r.datetime, '27-12-2015 21:08:15').group(0)
import re
class recomp:
"""ReComp lets you build regular expressions easily and reuse them.
"""
def __init__(self):
self.__dict__['_dict'] = {}
self.__dict__['_tags'] = re.compile('(?P<x>[^\\\\]?)\{\s*(?P<tagname>[a-zA-Z_][a-zA-Z_0-9]*)\s*\}')
def __setattr__(self, name, value):
if not isinstance(value, basestring):
raise TypeError('Value is not an string: %r' % value)
self._dict[name] = value
def __getattr__(self, name):
if name not in self._dict:
raise AttributeError("recomp instance has no attribute '%s'" % name)
def fn(mo):
return mo.groupdict()['x'] + getattr(self, mo.groupdict()['tagname'])
return self._tags.sub(fn, self._dict[name])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.