Completed
Push — master ( 74c8ad...722000 )
by Fabio
01:36
created

benedict.core.match.match()   A

Complexity

Conditions 3

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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