diff --git a/piiregex.py b/piiregex.py index 9bb758c..2cfc141 100644 --- a/piiregex.py +++ b/piiregex.py @@ -76,32 +76,39 @@ def __init__(self, text=""): self.text = text # Build class attributes of callables. - for k, v in regexes.items(): - setattr(self, k, regex(self, v)(self)) + self.__build_regex_class_attributes() if text: - for key in regexes.keys(): - method = getattr(self, key) - setattr(self, key, method()) + self.__build_class_attributes_callables() def any_match(self, text=""): - """Scan through all available matches and try to match. + """Scan through all available regexes and return whether we found any. """ + return True if self.matches(text=text) else False + + def matches(self, text=""): + """Scan through all available regexes and return a list of matches.""" if text: self.text = text # Regenerate class attribute callables. - for k, v in regexes.items(): - setattr(self, k, regex(self, v)(self)) - for key in regexes.keys(): - method = getattr(self, key) - setattr(self, key, method()) + self.__build_regex_class_attributes() + self.__build_class_attributes_callables() - matches = [] + results = [] for match in regexes.keys(): - # If we've got a result, add it to matches. + # If we've got a match, add it to results. if getattr(self, match): - matches.append(match) + results.append(match) + return results - return True if matches else False + def __build_regex_class_attributes(self): + """Build regex class attributes.""" + for k, v in regexes.items(): + setattr(self, k, regex(self, v)(self)) + def __build_class_attributes_callables(self): + """Build callable class attributes.""" + for key in regexes.keys(): + method = getattr(self, key) + setattr(self, key, method()) diff --git a/setup.py b/setup.py index 0f255ea..dcd339a 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ from distutils.core import setup -setup(name="piiregex", version="0.0.2", py_modules=["piiregex"]) +setup(name="piiregex", version="0.0.3", py_modules=["piiregex"]) diff --git a/test_piiregex.py b/test_piiregex.py index 28ad276..a35e4f7 100644 --- a/test_piiregex.py +++ b/test_piiregex.py @@ -182,3 +182,24 @@ def test_any_match_using_init_method(): parsed_text = PiiRegex('asdasdasdasdasd') assert parsed_text.any_match() is False + +def test_matches(pii_regex): + # This matches a phone number and a zip code. + matches = pii_regex.matches('07123 123123') + assert len(matches) == 2 + assert 'ukphones' in matches + assert 'zip_codes' in matches + # This should match nothing. + assert pii_regex.matches('asdasdasdasdasd') == [] + + +def test_matches_using_init_method(): + # This matches a phone number and a zip code. + parsed_text = PiiRegex('07123 123123') + matches = parsed_text.matches() + assert len(matches) == 2 + assert 'ukphones' in matches + assert 'zip_codes' in matches + # This should match nothing. + parsed_text = PiiRegex('asdasdasdasdasd') + assert parsed_text.matches() == []