Skip to content

Commit e5cf41c

Browse files
committed
simplify matchplus and matchstar
`matchplus` can be simplified by only modifying `matchlength` once the complete match is successful. This means it doesn't have to rewind `matchlength` as it iterates through each possible `matchpattern`. This also means it keeps `matchlength` unmodified if it doesn't return a match. Because of this last part, this also means that `matchstar` can leverage `matchplus` which reduces it to single line of code `return matchplus(...) || matchpattern(..)`.
1 parent 711981b commit e5cf41c

File tree

1 file changed

+7
-23
lines changed

1 file changed

+7
-23
lines changed

re.c

+7-23
Original file line numberDiff line numberDiff line change
@@ -397,42 +397,26 @@ static int matchone(regex_t p, char c)
397397
}
398398
}
399399

400-
static int matchstar(regex_t p, regex_t* pattern, const char* text, int* matchlength)
400+
static int matchplus(regex_t p, regex_t* pattern, const char* text, int* matchlength)
401401
{
402-
int prelen = *matchlength;
403402
const char* prepoint = text;
404403
while ((text[0] != '\0') && matchone(p, *text))
405404
{
406405
text++;
407-
(*matchlength)++;
408406
}
409-
while (text >= prepoint)
407+
for (; text > prepoint; text--)
410408
{
411-
if (matchpattern(pattern, text--, matchlength))
409+
if (matchpattern(pattern, text, matchlength)) {
410+
*matchlength += text - prepoint;
412411
return 1;
413-
(*matchlength)--;
412+
}
414413
}
415-
416-
*matchlength = prelen;
417414
return 0;
418415
}
419416

420-
static int matchplus(regex_t p, regex_t* pattern, const char* text, int* matchlength)
417+
static int matchstar(regex_t p, regex_t* pattern, const char* text, int* matchlength)
421418
{
422-
const char* prepoint = text;
423-
while ((text[0] != '\0') && matchone(p, *text))
424-
{
425-
text++;
426-
(*matchlength)++;
427-
}
428-
while (text > prepoint)
429-
{
430-
if (matchpattern(pattern, text--, matchlength))
431-
return 1;
432-
(*matchlength)--;
433-
}
434-
435-
return 0;
419+
return matchplus(p, pattern, text, matchlength) || matchpattern(pattern, text, matchlength);
436420
}
437421

438422
static int matchquestion(regex_t p, regex_t* pattern, const char* text, int* matchlength)

0 commit comments

Comments
 (0)