From b9dade270124d8a56b34064f85034ccb011de4e1 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Sun, 5 Jan 2025 10:46:30 +0100 Subject: [PATCH] Feat: add extract_values_from_pattern --- plesna/libs/__init__.py | 0 plesna/libs/string_tools.py | 18 ++++++++++++++++++ tests/libs/__init__.py | 0 tests/libs/test_string_tools.py | 18 ++++++++++++++++++ 4 files changed, 36 insertions(+) create mode 100644 plesna/libs/__init__.py create mode 100644 plesna/libs/string_tools.py create mode 100644 tests/libs/__init__.py create mode 100644 tests/libs/test_string_tools.py diff --git a/plesna/libs/__init__.py b/plesna/libs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plesna/libs/string_tools.py b/plesna/libs/string_tools.py new file mode 100644 index 0000000..62b732d --- /dev/null +++ b/plesna/libs/string_tools.py @@ -0,0 +1,18 @@ +import re + + +class StringToolsError(ValueError): + pass + + +def extract_values_from_pattern(pattern, string): + regex = re.sub(r"{(.+?)}", r"(?P<_\1>.+)", pattern) + + search = re.search(regex, string) + if search: + values = list(search.groups()) + keys = re.findall(r"{(.+?)}", pattern) + _dict = dict(zip(keys, values)) + return _dict + + raise StringToolsError(f"Can't parse '{string}' with the pattern '{pattern}'") diff --git a/tests/libs/__init__.py b/tests/libs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/libs/test_string_tools.py b/tests/libs/test_string_tools.py new file mode 100644 index 0000000..b8ed4ca --- /dev/null +++ b/tests/libs/test_string_tools.py @@ -0,0 +1,18 @@ +import pytest + +from plesna.libs.string_tools import StringToolsError, extract_values_from_pattern + + +def test_extract_values_from_pattern(): + source = "id:truc-bidule-machin" + pattern = "id:{champ1}-{champ2}-machin" + + assert extract_values_from_pattern(pattern, source) == {"champ1": "truc", "champ2": "bidule"} + + +def test_extract_values_from_pattern_no_match(): + source = "id:truc-bidule" + pattern = "id:{champ1}-{champ2}-machin" + + with pytest.raises(StringToolsError): + extract_values_from_pattern(pattern, source)