Skip to content

Commit a24fabb

Browse files
dpgeorgenotro
authored andcommitted
extmod/modure: Add match.groups() method, and tests.
This feature is controlled at compile time by MICROPY_PY_URE_MATCH_GROUPS, disabled by default. Thanks to @dmazzella for the original patch for this feature; see adafruit#3770.
1 parent 3792581 commit a24fabb

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

extmod/modure.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,28 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) {
7777
}
7878
MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group);
7979

80+
#if MICROPY_PY_URE_MATCH_GROUPS
81+
82+
STATIC mp_obj_t match_groups(mp_obj_t self_in) {
83+
mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in);
84+
if (self->num_matches <= 1) {
85+
return mp_const_empty_tuple;
86+
}
87+
mp_obj_tuple_t *groups = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->num_matches - 1, NULL));
88+
for (int i = 1; i < self->num_matches; ++i) {
89+
groups->items[i - 1] = match_group(self_in, MP_OBJ_NEW_SMALL_INT(i));
90+
}
91+
return MP_OBJ_FROM_PTR(groups);
92+
}
93+
MP_DEFINE_CONST_FUN_OBJ_1(match_groups_obj, match_groups);
94+
95+
#endif
96+
8097
STATIC const mp_rom_map_elem_t match_locals_dict_table[] = {
8198
{ MP_ROM_QSTR(MP_QSTR_group), MP_ROM_PTR(&match_group_obj) },
99+
#if MICROPY_PY_URE_MATCH_GROUPS
100+
{ MP_ROM_QSTR(MP_QSTR_groups), MP_ROM_PTR(&match_groups_obj) },
101+
#endif
82102
};
83103

84104
STATIC MP_DEFINE_CONST_DICT(match_locals_dict, match_locals_dict_table);

py/mpconfig.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1164,6 +1164,10 @@ typedef double mp_float_t;
11641164
#define MICROPY_PY_URE (0)
11651165
#endif
11661166

1167+
#ifndef MICROPY_PY_URE_MATCH_GROUPS
1168+
#define MICROPY_PY_URE_MATCH_GROUPS (0)
1169+
#endif
1170+
11671171
#ifndef MICROPY_PY_UHEAPQ
11681172
#define MICROPY_PY_UHEAPQ (0)
11691173
#endif

tests/extmod/ure_groups.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# test match.groups()
2+
3+
try:
4+
import ure as re
5+
except ImportError:
6+
try:
7+
import re
8+
except ImportError:
9+
print("SKIP")
10+
raise SystemExit
11+
12+
try:
13+
m = re.match(".", "a")
14+
m.groups
15+
except AttributeError:
16+
print('SKIP')
17+
raise SystemExit
18+
19+
20+
m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567')
21+
print(m.groups())
22+
23+
m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567')
24+
print(m.groups())
25+
26+
# optional group that matches
27+
print(re.match(r'(a)?b(c)', 'abc').groups())
28+
29+
# optional group that doesn't match
30+
print(re.match(r'(a)?b(c)', 'bc').groups())
31+
32+
# only a single match
33+
print(re.match(r'abc', 'abc').groups())

0 commit comments

Comments
 (0)