30 lines
1.0 KiB
Python

import regex
class RegexEditCol:
def __init__(self, match, replace_with, matching_group_rearange: bool = False, match_none: bool = False):
self.match = match
self.replace_with = replace_with
self.matching_group_rearange = matching_group_rearange
self.match_none = match_none
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:
if self.match_none:
entry.value = self.replace_with
return entry
if self.matching_group_rearange:
entry.value = self._reorder(value)
else:
entry.value = regex.sub(self.match, self.replace_with, value)
return entry