Created
September 15, 2014 11:07
-
-
Save kwatch/da356bbdf056e39be1ff to your computer and use it in GitHub Desktop.
Implementation of re.matching()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import re | |
class matching(object): | |
def __init__(self, string): | |
self.string = string | |
self.matched = None | |
def match(self, pattern, flags=0): | |
self.matched = re.compile(pattern, flags).match(self.string) | |
return self.matched | |
def search(self, pattern, flags=0): | |
self.matched = re.compile(pattern, flags).search(self.string) | |
return self.matched | |
def group(self, *args): | |
return self.matched.group(*args) | |
def groups(self, default=None): | |
return self.matched.groups(default) | |
def groupdict(self, default=None): | |
return self.matched.groupdict(default) | |
if __name__ == '__main__': | |
m = matching("2014/09/14") | |
if m.match(r'^(\d\d\d\d)-(\d\d)-(\d\d)$'): | |
Y, M, D = m.groups() | |
elif m.match(r'^(\d\d)/(\d\d)/(\d\d\d\d)$'): | |
M, D, Y = m.groups() | |
elif m.match(r'^(\d\d\d\d)/(\d\d)/(\d\d)$'): | |
Y, M, D = m.groups() | |
else: | |
raise ValueError("not matched") | |
print("year: %s, month: %s, day: %s" % (Y, M, D)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment