benedict.core.match.match()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 14
rs 9.85
c 0
b 0
f 0
cc 3
nop 4
1
import re
2
3
from benedict.core.keypaths import keypaths
4
from benedict.utils import type_util
5
6
7
def match(d, pattern, separator=".", indexes=True):
8
    if type_util.is_regex(pattern):
9
        regex = pattern
10
    elif type_util.is_string(pattern):
11
        # all indexes wildcard support
12
        pattern = re.sub(r"([\*]{1})", "(.)*", pattern)
13
        # escape square brackets
14
        pattern = re.sub(r"(\[([^\[\]]*)\])", "\\[\\g<2>\\]", pattern)
15
        regex = re.compile(pattern, flags=re.DOTALL)
16
    else:
17
        raise ValueError(f"Expected regex or string, found: {type(pattern)}")
18
    kps = keypaths(d, separator=separator, indexes=indexes)
19
    values = [d.get(kp) for kp in kps if regex.match(kp)]
20
    return values
21