Feat: add extract_values_from_pattern
This commit is contained in:
parent
ed8f91d78b
commit
b9dade2701
0
plesna/libs/__init__.py
Normal file
0
plesna/libs/__init__.py
Normal file
18
plesna/libs/string_tools.py
Normal file
18
plesna/libs/string_tools.py
Normal file
@ -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}'")
|
0
tests/libs/__init__.py
Normal file
0
tests/libs/__init__.py
Normal file
18
tests/libs/test_string_tools.py
Normal file
18
tests/libs/test_string_tools.py
Normal file
@ -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)
|
Loading…
Reference in New Issue
Block a user