python-benedict/benedict/core/match.py

21 lines
721 B
Python
Raw Permalink Normal View History

import re
2020-09-22 12:10:59 +00:00
from benedict.core.keypaths import keypaths
from benedict.utils import type_util
2022-02-13 10:35:43 +00:00
def match(d, pattern, separator=".", indexes=True):
2020-09-22 12:10:59 +00:00
if type_util.is_regex(pattern):
regex = pattern
elif type_util.is_string(pattern):
# all indexes wildcard support
2022-02-13 10:35:43 +00:00
pattern = re.sub(r"([\*]{1})", "(.)*", pattern)
2020-09-22 12:10:59 +00:00
# escape square brackets
2022-02-13 10:35:43 +00:00
pattern = re.sub(r"(\[([^\[\]]*)\])", "\\[\\g<2>\\]", pattern)
2020-09-22 12:10:59 +00:00
regex = re.compile(pattern, flags=re.DOTALL)
else:
raise ValueError(f"Expected regex or string, found: {type(pattern)}")
2020-09-22 12:10:59 +00:00
kps = keypaths(d, separator=separator, indexes=indexes)
values = [d.get(kp) for kp in kps if regex.match(kp)]
return values