Skip to content

Instantly share code, notes, and snippets.

@StevenLooman
Created July 20, 2012 18:59
Show Gist options
  • Save StevenLooman/3152578 to your computer and use it in GitHub Desktop.
Save StevenLooman/3152578 to your computer and use it in GitHub Desktop.
The classic match(), version in Smallworld/Magik
#/* matchere: search for regexp at beginning of text */
#int matchhere(char *regexp, char *text) {
# if (regexp[0] == '\0')
# return 1;
# if (regexp[1] == '*')
# return matchstar(regexp[0], regexp+2, text);
# if (regexp[0] == '$' && regexp[1] == '\0')
# return *text == '\0';
# if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text))
# return matchhere(regexp+1, text+1);
# return 0;
#}
_global matchhere <<
_proc @matchhere(regexp, text)
_if regexp.empty?
_then
_return _true
_endif
_if regexp.size >= 2 _andif regexp[2] = %*
_then
_return matchstar(regexp[1], regexp.subseq(3), text)
_endif
_if regexp[1] = %$ _andif regexp.size = 1
_then
_return text.empty?
_endif
_if _not text.empty? _andif (regexp[1] = %. _orif regexp[1] = text[1])
_then
_return matchhere(regexp.subseq(2), text.subseq(2))
_endif
_return _false
_endproc
$
#/* match: search for regexp anywhere in text */
#int match(char *regexp, char *text) {
# if (regexp[0] == '^')
# return matchhere(regexp+1, text);
# do { / must look even if string is empty /
# if (matchhere(regexp, text))
# return 1;
# } while (*text++ != '\0');
# return 0;
#}
_global match <<
_proc @match(regexp, text)
_if _not regexp.empty? _andif regexp[1] = %^
_then
_return matchhere(regexp.subseq(2), text)
_endif
_loop
_if matchhere(regexp, text)
_then
_return _true
_endif
_if text.size < 2
_then
_leave
_endif
text << text.subseq(2)
_endloop
_return _false
_endproc
$
#/* matchstar: search for c*regexp at beginning of text */
#int matchstar(int c, char *regexp, char *text) {
# do { / a * matches zero or more instances */
# if (matchhere(regexp, text))
# return 1;
# } while (*text != '\0' && (*text++ == c || c == '.'));
# return 0;
#}
_global matchstar <<
_proc @matchstar(c, regexp, text)
_loop
_if matchhere(regexp, text)
_then
_return _true
_endif
_if _not (_not text.empty? _andif (text[1] = c _orif c = %.))
_then
_leave
_endif
text << text.subseq(2)
_endloop
_return _false
_endproc
$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment