From 2617b8270f04ea331f1d1621d5b99a1af6ac07a8 Mon Sep 17 00:00:00 2001 From: EwenBALOUIN Date: Tue, 19 Dec 2023 14:57:52 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20LeftPadZeroes=20-=20add=20regex=20f?= =?UTF-8?q?ield=20Can=20use=20left=20pad=20when=20regex=20match?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- magicparse/pre_processors.py | 8 ++++++-- tests/test_pre_processors.py | 7 +++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/magicparse/pre_processors.py b/magicparse/pre_processors.py index cc1f25f..eba5657 100644 --- a/magicparse/pre_processors.py +++ b/magicparse/pre_processors.py @@ -1,4 +1,5 @@ import re +from typing import Optional from .transform import Transform @@ -22,11 +23,14 @@ def build(cls, options: dict) -> "PreProcessor": class LeftPadZeroes(PreProcessor): - def __init__(self, width: int) -> None: + def __init__(self, width: int, regex: Optional[str] = None) -> None: self.width = width + self.regex = regex def apply(self, value: str) -> str: - return value.zfill(self.width) + if self.regex is None or (self.regex and re.match(self.regex, value)): + return value.zfill(self.width) + return value @staticmethod def key() -> str: diff --git a/tests/test_pre_processors.py b/tests/test_pre_processors.py index 2f5fb6e..35c73d7 100644 --- a/tests/test_pre_processors.py +++ b/tests/test_pre_processors.py @@ -78,6 +78,13 @@ def test_pad(self): ) assert pre_processor.apply("abc") == "0000000abc" + def test_pad_with_regex(self): + pre_processor = PreProcessor.build( + {"name": "left-pad-zeroes", "parameters": {"width": 10, "regex" : "[a-z]{7}"}} + ) + assert pre_processor.apply("abc") == "abc" + assert pre_processor.apply("abcdefg") == "000abcdefg" + class TestMap(TestCase): def test_unknown_input(self):