diff --git a/benedict/core/match.py b/benedict/core/match.py index 514fe914..182769e6 100644 --- a/benedict/core/match.py +++ b/benedict/core/match.py @@ -21,6 +21,8 @@ def match( pattern = re.sub(r"([\*]{1})", "(.)*", pattern) # escape square brackets pattern = re.sub(r"(\[([^\[\]]*)\])", "\\[\\g<2>\\]", pattern) + # anchor to end so the full keypath must be consumed + pattern = pattern + "$" regex = re.compile(pattern, flags=re.DOTALL) else: raise ValueError(f"Expected regex or string, found: {type(pattern)}") diff --git a/tests/core/test_match.py b/tests/core/test_match.py index 4147c05c..08bc9123 100644 --- a/tests/core/test_match.py +++ b/tests/core/test_match.py @@ -57,6 +57,17 @@ def test_match_with_regex_pattern(self) -> None: ] self.assertEqual(values, expected_values) + def test_match_with_suffix_wildcard(self) -> None: + # Suffix wildcard like "*.jpg" must not match "IMG_0001.jpg.bak" – + # i.e. the full keypath must be consumed, not just a prefix. + d = { + "IMG_0001.jpg": "IMG_0001.jpg", + "IMG_0001.jpg.bak": "IMG_0001.jpg.bak", + "DOC_0001.pdf": "DOC_0001.pdf", + } + values = _match(d, "*.jpg") + self.assertEqual(values, ["IMG_0001.jpg"]) + def test_match_with_invalid_pattern(self) -> None: d = self._get_dict() with self.assertRaises(ValueError):