fledermaus/table_handler/commands/regex_edit_col.py

26 lines
851 B
Python

import regex
class RegexEditCol:
def __init__(self, match, replace_with, matching_group_rearange: bool = False):
self.match = match
self.replace_with = replace_with
self.matching_group_rearange = matching_group_rearange
def _reorder(self, value: str):
matches = regex.match(self.match, value)
res = None
if matches:
for i, match in enumerate(matches.groups([])):
res = (res if res else self.replace_with).replace(f"{{{{% {i} %}}}}", match)
return res if res else value
def execute_on_cell(self, entry) -> str:
value = entry.value
if value is None:
return value
if self.matching_group_rearange:
return self._reorder(value)
return regex.sub(self.match, self.replace_with, value)