From 8642b73ba1285a4fd12b5eeee403625c6a4f07fc Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sun, 4 Dec 2022 12:34:52 +0100 Subject: [PATCH] misc: Add multi_regex_edit() Signed-off-by: Jan Lindemann --- tools/python/jwutils/misc.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tools/python/jwutils/misc.py b/tools/python/jwutils/misc.py index 6c459bf..3b243f6 100644 --- a/tools/python/jwutils/misc.py +++ b/tools/python/jwutils/misc.py @@ -114,6 +114,38 @@ def commit_tmpfile(tmp: str, path: str) -> None: # export log.slog(log.NOTICE, "saving {}".format(path), caller=caller) os.rename(path + '.tmp', path) +def multi_regex_edit(spec, strings): # export + for cmd in spec: + if len(cmd) < 2: + raise Exception('Invalid command in multi_regex_edit(): {}'.format(str(cmd))) + if cmd[0] == 'sub': + rx = re.compile(cmd[1]) + replacement = cmd[2] + r = [] + for l in strings: + r.append(re.sub(rx, replacement, l)) + strings = r + continue + if cmd[0] == 'del': + rx = re.compile(cmd[1]) + r = [] + for l in strings: + if rx.search(l) is not None: + continue + r.append(l) + strings = r + continue + if cmd[0] == 'match': + rx = re.compile(cmd[1]) + r = [] + for l in strings: + if rx.search(l) is not None: + r.append(l) + strings = r + continue + raise Exception('Invalid command in multi_regex_edit(): {}'.format(str(cmd))) + return strings + def dump(prio: int, objects: Iterable, *args, **kwargs) -> None: # export caller = log.get_caller_pos(kwargs=kwargs) log.slog(prio, ",---------- {}".format(' '.join(args)), caller=caller)