def find(self, str_val, max_results): """ Tries to find all occurrences of the template in the provided string. Stops after the maximum number of results is reached. """ str_val = str_val.strip() results = list() for matcher in self._pattern.finditer(str_val): if not StringUtils.is_delimited(str_val, matcher.start(), matcher.end()): continue match_result = MatchResult(matcher.start(), matcher.end()) for slot_key in self._slots.keys(): filled_value = matcher.group(self._slots[slot_key]).strip() # quick-fix to handle some rare cases where the occurrence found # by the regex leads to unbalanced parentheses or brackets. # TODO: check whether this is a bug or not. if not StringUtils.check_form(filled_value) and self.permutate_pattern(): return self.find(str_val, max_results) match_result.add_pair(slot_key, filled_value) results.append(match_result) if len(results) >= max_results: break return results
def find(self, str_val, max_results): """ Searches for all possible occurrences of the template in the provided string. Stops if the maximum number of results is reached. """ str_val = str_val.strip() results = [] start = 0 while True: try: start = str_val.index(self._str_val, start) end = start + len(self._str_val) if not self._whole or StringUtils.is_delimited( str_val, start, end): results.append(MatchResult(start, end)) if len(results) >= max_results: break start = end except ValueError: break return results