Skip to content

Instantly share code, notes, and snippets.

@jdevera
Last active December 29, 2015 07:58
Show Gist options
  • Save jdevera/7639577 to your computer and use it in GitHub Desktop.
Save jdevera/7639577 to your computer and use it in GitHub Desktop.
A python class to do saner "if..match"
class Matcher(object):
"""
A more convenient way to check regex matches. It holds the latest match
result for further checks.
The current regex match mechanism does not allow for checking matches in
if/elif chains. Thanks to Matcher now one can do this:
>>> m = Matcher()
>>> s = "ba"
>>> if m.match(r'^a(.)', s):
>>> print "A" + m.group(0)
>>> elif m.match(re.compile(r'^b(.)', s):
>>> print "B" + m.group(0)
Ba
Matcher class
Copyright (C) 2013 Jacobo de Vera
MIT license
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
def __init__(self):
self.clear()
def match(self, regex, string):
self.m = self._compile(regex).match(string)
if self.m is None:
return False
return True
def search(self, regex, string):
self.m = self._compile(regex).search(string)
if self.m is None:
return False
return True
def group(self, n):
if self.m is None:
return None
return self.m.group(n)
def clear(self):
self.m = None
def _compile(self, regex):
if isinstance(regex, (str, bytes)):
return re.compile(regex)
return regex
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment