Skip to content

Commit 6cb6947

Browse files
committed
extmod/ure: Correctly return None when a group has no match.
See issue adafruit#1122.
1 parent 2a68c2c commit 6cb6947

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

extmod/modure.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,10 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) {
6565
}
6666

6767
const char *start = self->caps[no * 2];
68+
if (start == NULL) {
69+
// no match for this group
70+
return mp_const_none;
71+
}
6872
return mp_obj_new_str(start, self->caps[no * 2 + 1] - start, false);
6973
}
7074
MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group);
@@ -97,6 +101,7 @@ STATIC mp_obj_t re_exec(bool is_anchored, uint n_args, const mp_obj_t *args) {
97101
subj.end = subj.begin + len;
98102
int caps_num = (self->re.sub + 1) * 2;
99103
mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char*, caps_num);
104+
memset(match->caps, 0, caps_num * sizeof(char*));
100105
int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored);
101106
if (res == 0) {
102107
m_del_var(mp_obj_match_t, char*, caps_num, match);
@@ -135,6 +140,7 @@ STATIC mp_obj_t re_split(uint n_args, const mp_obj_t *args) {
135140
mp_obj_t retval = mp_obj_new_list(0, NULL);
136141
const char **caps = alloca(caps_num * sizeof(char*));
137142
while (true) {
143+
memset(caps, 0, caps_num * sizeof(char*));
138144
int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false);
139145

140146
// if we didn't have a match, or had an empty match, it's time to stop

tests/extmod/ure_group.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def print_groups(match):
1010
try:
1111
i = 0
1212
while True:
13-
print(m.group(i))
13+
print(match.group(i))
1414
i += 1
1515
except IndexError:
1616
pass
@@ -20,3 +20,9 @@ def print_groups(match):
2020

2121
m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567')
2222
print_groups(m)
23+
24+
# optional group that matches
25+
print_groups(re.match(r'(a)?b(c)', 'abc'))
26+
27+
# optional group that doesn't match
28+
print_groups(re.match(r'(a)?b(c)', 'bc'))

0 commit comments

Comments
 (0)