Skip to content

Commit

Permalink
simplify matchplus and matchstar
Browse files Browse the repository at this point in the history
`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(..)`.
  • Loading branch information
marler8997 committed Mar 7, 2021
1 parent 711981b commit d0c52ea
Showing 1 changed file with 5 additions and 21 deletions.
26 changes: 5 additions & 21 deletions re.c
Original file line number Diff line number Diff line change
Expand Up @@ -399,22 +399,7 @@ static int matchone(regex_t p, char c)

static int matchstar(regex_t p, regex_t* pattern, const char* text, int* matchlength)
{
int prelen = *matchlength;
const char* prepoint = text;
while ((text[0] != '\0') && matchone(p, *text))
{
text++;
(*matchlength)++;
}
while (text >= prepoint)
{
if (matchpattern(pattern, text--, matchlength))
return 1;
(*matchlength)--;
}

*matchlength = prelen;
return 0;
return matchplus(p, pattern, text, matchlength) || matchpattern(pattern, text, matchlength);
}

static int matchplus(regex_t p, regex_t* pattern, const char* text, int* matchlength)
Expand All @@ -423,15 +408,14 @@ static int matchplus(regex_t p, regex_t* pattern, const char* text, int* matchle
while ((text[0] != '\0') && matchone(p, *text))
{
text++;
(*matchlength)++;
}
while (text > prepoint)
for (; text > prepoint; text--)
{
if (matchpattern(pattern, text--, matchlength))
if (matchpattern(pattern, text, matchlength)) {
*matchlength += text - prepoint;
return 1;
(*matchlength)--;
}
}

return 0;
}

Expand Down

0 comments on commit d0c52ea

Please sign in to comment.