def _replace(self, match: re.Match, replacement: str, operation: Callable) -> str: groups = match.groupdict() if '%s' in replacement: token = groups.get('token') prefix = '' suffix = '' if token: # Looks like prefix/suffix groups matter only if token-group # was in a pattern prefix = groups.get('prefix', '') suffix = groups.get('suffix', '') else: token = match.group() alias = operation(token) replacement = replacement.replace('%s', prefix + alias + suffix) replacement = self._fix_replacement_groups(replacement) try: return match.expand(replacement) except IndexError as error: raise TransformerError(f'Invalid replacement: {error}')
def replace(match: re.Match) -> str: variables = match.groupdict() variable_parts = {} for capture, (variable, directive) in date_patterns.captures.items(): parts = variable_parts.setdefault(variable, {}) parts[directive] = variables[capture] for variable, parts in variable_parts.items(): directives, values = zip(*parts.items()) fmt = " ".join(map("%{}".format, directives)) value = " ".join(values) variables[variable] = datetime.datetime.strptime(value, fmt) return match.expand(replacement.format_map(variables))
def expand_match(match: re.Match, value: Any) -> Any: """ Return the value obtained by doing backslash substitution on the template string template :param match: The match object. :param value: The template value. :return: The value replaced. """ if isinstance(value, dict): return { expand_match(match, k): expand_match(match, v) for k, v in value.items() } elif isinstance(value, list): return [expand_match(match, v) for v in value] elif isinstance(value, str): return match.expand(value.replace(r'\0', r'\g<0>')) else: return value
def expand_template(match: re.Match, template: Any) -> Any: """ Return the string obtained by doing backslash substitution on the template. :param match: The match object. :param template: The template. :return: The template replaced with backslash substitution symbols. """ if template is None: return match.group(0) elif isinstance(template, str): return match.expand(template.replace(r'\0', r'\g<0>')) elif isinstance(template, list): return [expand_template(match, t) for t in template] elif isinstance(template, dict): return {expand_template(match, k): expand_template(match, v) for k, v in template.items()} else: return template
def __call__(self, match: re.Match): matched = match.group(0) replaced = match.expand(self.replacement).format( self.manager._generate_id(matched)) self.occurrences.append((matched, replaced)) return replaced
def validate_replacement(re_match: re.Match, replacement_pattern: str): """Test if it's valid in terms of regex rules""" simplified = replacement_pattern.replace('\\L', '').replace('\\U', '') simplified = re.sub(r'\\P(\d+)', '', simplified) re_match.expand(simplified)