2020-09-22 12:10:59 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
from benedict.core.keypaths import keypaths
|
|
|
|
from benedict.utils import type_util
|
|
|
|
|
|
|
|
import re
|
|
|
|
|
|
|
|
|
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:
|
2022-02-13 10:35:43 +00:00
|
|
|
raise ValueError("Expected regex or string, found: {}".format(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
|