home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 2 / 2839 < prev    next >
Internet Message Format  |  1991-02-22  |  16KB

  1. From: johnk@wrq.com
  2. Newsgroups: alt.sources
  3. Subject: REGEX Globber (Wild Card Matching)
  4. Message-ID: <17016@milton.u.washington.edu>
  5. Date: 23 Feb 91 01:49:30 GMT
  6.  
  7. 02-24-91 Seattle, WA
  8.  
  9. Hmm. Choke. (Foot in mouth). After griping about buggy routines and
  10. literally seconds after posting this code the first time,  I received
  11. a wonderful new test evaluation tool which allows you to perform
  12. coverage analysis during testing.  Sure enough I found that about
  13. 25% of the paths in the program were never traversed in my current
  14. test battery.  After swallowing my (overly large) pride and coming
  15. up with a test battery which covered the entire path of the program
  16. I found a couple of minor logic bugs involving literal escapes (\)
  17. within other patterns (ie [..] and * sequences).  I have repackaged
  18. these routines and included also the makefile I use and the test
  19. battery I use to make things a bit easier.
  20.  
  21.                                 jbk
  22.  
  23.  
  24. Here is a *IX wildcard globber I butchered, hacked and cajoled together
  25. after seeing and hearing about and becoming disgusted with several similar
  26. routines which had one or more of the following attributes:  slow, buggy,
  27. required large levels of recursion on matches, required grotesque levels
  28. of recursion on failing matches using '*', full of caveats about usability
  29. or copyrights.
  30.  
  31. I submit this without copyright and with the clear understanding that
  32. this code may be used by anyone, for any reason, with any modifications
  33. and without any guarantees, warrantee or statements of usability of any
  34. sort.
  35.  
  36. Having gotten those cow chips out of the way, these routines are fairly
  37. well tested and reasonably fast.  I have made an effort to fail on all
  38. bad patterns and to quickly determine failing '*' patterns.  This parser
  39. will also do quite a bit of the '*' matching via quick linear loops versus
  40. the standard blind recursive descent.
  41.  
  42. This parser has been submitted to profilers at various stages of development
  43. and has come through quite well.  If the last millisecond is important to
  44. you then some time can be shaved by using stack allocated variables in
  45. place of many of the pointer follows (which may be done fairly often) found
  46. in regex_match and regex_match_after_star (ie *p, *t).
  47.  
  48. No attempt is made to provide general [pat,pat] comparisons.  The specific
  49. subcases supplied by these routines is [pat,text] which is sufficient
  50. for the large majority of cases (should you care).
  51.  
  52. Since regex_match may return one of three different values depending upon
  53. the pattern and text I have made a simple shell for convenience (match()).
  54. Also included is an is_pattern routine to quickly check a potential pattern
  55. for regex special characters.  I even placed this all in a header file for
  56. you lazy folks!
  57.  
  58. Having said all that, here is my own reinvention of the wheel.  Please
  59. enjoy it's use and I hope it is of some help to those with need ....
  60.  
  61.  
  62.                                 jbk
  63.  
  64.  
  65. ==================== BEGIN of Listing ====================
  66.  
  67.  
  68. Checksum: 2543766536   (verify or update this with "brik")
  69.  
  70.  
  71. ==================== MATCHMAK ====================
  72.  
  73. #
  74. #
  75. # Makefile for match.c
  76. #
  77. # Created 01-20-91 JBK
  78. # Last Modified 02-13-91 JBK
  79. #
  80. #
  81.  
  82. CC = cl
  83.  
  84. #
  85. # This is FLAGS for optimized version
  86. #FLAGS = /c /AL /G0 /F 0FFF /Ox /W4
  87.  
  88. #
  89. # This is FLAGS for optimized version with main
  90. #FLAGS = /D TEST /AL /G0 /F 0FFF /Ox /W4
  91.  
  92. #
  93. # This is FLAGS for debugging versions with main
  94. FLAGS = /D TEST /AL /G0 /F 0FFF /Od /W4 /Zi /qc
  95.  
  96.  
  97. match.exe: match.c match.h
  98.     $(CC) $(FLAGS) match.c
  99.  
  100.  
  101.  
  102.  
  103. ==================== MATCHTST.BAT ====================
  104.  
  105. @echo The following tests should match
  106. match test? testy
  107. match test* test
  108. match tes*t test
  109. match *test test
  110. match t*s*t test
  111. match t*s*t tesseract
  112. match t?s? test
  113. match ?s*t psyot
  114. match [a-z]s*t asset
  115. match s[!gh]t set
  116. match t[a-ce]st test
  117. match tea[ea-c]up teacup
  118. match [a-fh-z]* jack
  119. match \i\** i*hello
  120. match [\[-\]] [
  121. match [a-z\\] \
  122. match [a-z%_] b
  123. match [\]] ]
  124. match \i?* itch
  125. match \i?* it
  126. match ?*?*?t test
  127. match ?*?*?*?* test
  128. match *\]*\**\?*\[ ]this*is?atest[
  129.  
  130. @echo The following tests should fail
  131. match hello
  132. match test test
  133. match \ test
  134. match t*s*t texxeract
  135. match t?st tst
  136. match test? test
  137. match s[!e]t set
  138. match [] ]
  139. match [ [
  140. match [\[-\] [
  141. match [a atest
  142. match [a- atest
  143. match [a-z atest
  144. match [a-]* atest
  145. match [a-fh-z jack
  146. match [a-fh-z\] jack
  147. match [a-fh-z] jack
  148. match ?*?*?t*? test
  149. match *????? test
  150.  
  151.  
  152.  
  153.  
  154. ==================== MATCH.H ====================
  155.  
  156. /*
  157.  EPSHeader
  158.  
  159.    File: match.h
  160.    Author: J. Kercheval
  161.    Created: Sat, 01/05/1991  22:27:18
  162. */
  163. /*
  164.  EPSRevision History
  165.  
  166.    J. Kercheval  Wed, 02/20/1991  22:28:37  Released to Public Domain
  167. */
  168.  
  169. /*
  170.    Wildcard Pattern Matching
  171. */
  172.  
  173. #ifndef BOOLEAN
  174. # define BOOLEAN int
  175. # define TRUE 1
  176. # define FALSE 0
  177. #endif
  178.  
  179. /*----------------------------------------------------------------------------
  180. *
  181. *  Match the pattern PATTERN against the string TEXT;
  182. *  return TRUE if it matches, FALSE otherwise.
  183. *
  184. *  A match means the entire string TEXT is used up in matching.
  185. *
  186. *  In the pattern string:
  187. *       `*' matches any sequence of characters
  188. *       `?' matches any character
  189. *       [SET] matches any character in the specified set,
  190. *       [!SET] or [^SET] matches any character not in the specified set.
  191. *
  192. *  Note: the standard regex character '+' (one or more) should by
  193. *        simulated by using "?*" which is equivelant here.
  194. *
  195. *  A set is composed of characters or ranges; a range looks like
  196. *  character hyphen character (as in 0-9 or A-Z).  [0-9a-zA-Z_] is the
  197. *  minimul set of characters allowed in the [..] pattern construct.
  198. *  Other characters are allowed (ie. 8 bit characters) if your system
  199. *  will support them.
  200. *
  201. *  To suppress the special syntactic significance of any of `[]*?!^-\',
  202. *  and match the character exactly, precede it with a `\'.
  203. *
  204. ----------------------------------------------------------------------------*/
  205.  
  206. BOOLEAN match (char *pattern, char *text);
  207.  
  208. /*----------------------------------------------------------------------------
  209. *
  210. * Return TRUE if PATTERN has any special wildcard characters
  211. *
  212. ----------------------------------------------------------------------------*/
  213.  
  214. BOOLEAN is_pattern (char *pattern);
  215.  
  216.  
  217.  
  218.  
  219. ==================== MATCH.C ====================
  220.  
  221. /*
  222.  EPSHeader
  223.  
  224.    File: match.c
  225.    Author: J. Kercheval
  226.    Created: Sat, 01/05/1991  22:21:49
  227. */
  228. /*
  229.  EPSRevision History
  230.  
  231.    J. Kercheval  Wed, 02/20/1991  22:29:01  Released to Public Domain
  232.    J. Kercheval  Fri, 02/22/1991  15:29:01  fix '\' bugs (two :( of them)
  233. */
  234.  
  235. /*
  236.    Wildcard Pattern Matching
  237. */
  238.  
  239.  
  240. #include "match.h"
  241.  
  242. #define ABORT 2     /* end of search indicator */
  243.  
  244. BOOLEAN regex_match_after_star (char *pattern, char *text);
  245.  
  246. /*----------------------------------------------------------------------------
  247. *
  248. * Return TRUE if PATTERN has any special wildcard characters
  249. *
  250. ----------------------------------------------------------------------------*/
  251.  
  252. BOOLEAN is_pattern (char *p)
  253. {
  254.     while ( *p ) {
  255.         switch ( *p++ ) {
  256.             case '?':
  257.             case '*':
  258.             case '[':
  259.                 return TRUE;
  260.             case '\\':
  261.                 if ( !*p++ ) return FALSE;
  262.         }
  263.     }
  264.     return FALSE;
  265. }
  266.  
  267.  
  268. /*----------------------------------------------------------------------------
  269. *
  270. *  Match the pattern PATTERN against the string TEXT;
  271. *  return TRUE if it matches, FALSE otherwise.
  272. *
  273. *  A match means the entire string TEXT is used up in matching.
  274. *
  275. *  In the pattern string:
  276. *       `*' matches any sequence of characters
  277. *       `?' matches any character
  278. *       [SET] matches any character in the specified set,
  279. *       [!SET] or [^SET] matches any character not in the specified set.
  280. *
  281. *  Note: the standard regex character '+' (one or more) should by
  282. *        simulated by using "?*" which is equivelant here.
  283. *
  284. *  A set is composed of characters or ranges; a range looks like
  285. *  character hyphen character (as in 0-9 or A-Z).  [0-9a-zA-Z_] is the
  286. *  minimul set of characters allowed in the [..] pattern construct.
  287. *  Other characters are allowed (ie. 8 bit characters) if your system
  288. *  will support them.
  289. *
  290. *  To suppress the special syntactic significance of any of `[]*?!^-\',
  291. *  and match the character exactly, precede it with a `\'.
  292. *
  293. ----------------------------------------------------------------------------*/
  294.  
  295. BOOLEAN regex_match ( register char *p, register char *t )
  296. {
  297.     register char range_start, range_end;  /* start and end in range */
  298.  
  299.     BOOLEAN invert;             /* is this [..] or [!..] */
  300.     BOOLEAN member_match;       /* have I matched the [..] construct? */
  301.     BOOLEAN loop;               /* should I terminate? */
  302.  
  303.     for ( ; *p; p++, t++ ) {
  304.  
  305.         /* if this is the end of the text then this is the end of the match */
  306.         if (!*t) {
  307.             return ( *p == '*' && *++p == '\0' ) ? TRUE : ABORT;
  308.         }
  309.  
  310.         /* determine and react to pattern type */
  311.         switch ( *p ) {
  312.  
  313.             /* single any character match */
  314.             case '?':
  315.                 break;
  316.  
  317.             /* multiple any character match */
  318.             case '*':
  319.                 return regex_match_after_star (p, t);
  320.  
  321.             /* [..] construct, single member/exclusion character match */
  322.             case '[': {
  323.  
  324.                 /* move to beginning of range */
  325.                 p++;
  326.  
  327.                 /* check if this is a member match or exclusion match */
  328.                 invert = FALSE;
  329.                 if ( *p == '!' || *p == '^') {
  330.                     invert = TRUE;
  331.                     p++;
  332.                 }
  333.  
  334.                 /* if closing bracket here or at range start then we have a
  335.                    malformed pattern */
  336.                 if ( *p == ']' ) {
  337.                     return ABORT;
  338.                 }
  339.  
  340.                 member_match = FALSE;
  341.                 loop = TRUE;
  342.  
  343.                 while ( loop ) {
  344.  
  345.                     /* if end of construct then loop is done */
  346.                     if (*p == ']') {
  347.                         loop = FALSE;
  348.                         continue;
  349.                     }
  350.  
  351.                     /* matching a '!', '^', '-', '\' or a ']' */
  352.                     if ( *p == '\\' ) {
  353.                         range_start = range_end = *++p;
  354.                     }
  355.                     else {
  356.                         range_start = range_end = *p;
  357.                     }
  358.  
  359.                     /* if end of pattern then bad pattern (Missing ']') */
  360.                     if (!range_start)
  361.                         return ABORT;
  362.  
  363.                     /* check for range bar */
  364.                     if (*++p == '-') {
  365.  
  366.                         /* get the range end */
  367.                         range_end = *++p;
  368.  
  369.                         /* if end of pattern or construct then bad pattern */
  370.                         if (range_end == '\0' || range_end == ']')
  371.                             return ABORT;
  372.  
  373.                         /* special character range end */
  374.                         if (range_end == '\\')
  375.                             range_end = *++p;
  376.  
  377.                         /* move just beyond this range */
  378.                         p++;
  379.                     }
  380.  
  381.                     /* if the text character is in range then match found.
  382.                        make sure the range letters have the proper
  383.                        relationship to one another before comparison */
  384.                     if ( range_start < range_end  ) {
  385.                         if (*t >= range_start && *t <= range_end) {
  386.                             member_match = TRUE;
  387.                             loop = FALSE;
  388.                         }
  389.                     }
  390.                     else {
  391.                         if (*t >= range_end && *t <= range_start) {
  392.                             member_match = TRUE;
  393.                             loop = FALSE;
  394.                         }
  395.                     }
  396.                 }
  397.  
  398.                 /* if there was a match in an exclusion set then no match */
  399.                 /* if there was no match in a member set then no match */
  400.                 if ((invert && member_match) ||
  401.                    !(invert || member_match))
  402.                     return FALSE;
  403.  
  404.                 /* if this is not an exclusion then skip the rest of the [...]
  405.                     construct that already matched. */
  406.                 if (member_match) {
  407.                     while (*p != ']') {
  408.  
  409.                         /* bad pattern (Missing ']') */
  410.                         if (!*p)
  411.                             return ABORT;
  412.  
  413.                         /* skip exact match */
  414.                         if (*p == '\\') {
  415.                             p++;
  416.                         }
  417.  
  418.                         /* move to next pattern char */
  419.                         p++;
  420.                     }
  421.                 }
  422.  
  423.                 break;
  424.             }
  425.  
  426.             /* next character is quoted and must match exactly */
  427.             case '\\':
  428.  
  429.                 /* move pattern pointer to quoted char and fall through */
  430.                 p++;
  431.  
  432.             /* must match this character exactly */
  433.             default:
  434.                 if (*p != *t)
  435.                     return FALSE;
  436.         }
  437.     }
  438.  
  439.     /* if end of text not reached then the pattern fails */
  440.     return !*t;
  441. }
  442.  
  443.  
  444. /*----------------------------------------------------------------------------
  445. *
  446. * recursively call regex_match with final segment of PATTERN and of TEXT.
  447. *
  448. ----------------------------------------------------------------------------*/
  449.  
  450. BOOLEAN regex_match_after_star (register char *p, register char *t)
  451. {
  452.     register BOOLEAN match;
  453.     register nextp;
  454.  
  455.     /* pass over existing ? and * in pattern */
  456.     while ( *p == '?' || *p == '*' ) {
  457.  
  458.         /* take one char for each ? */
  459.         if ( *p == '?' ) {
  460.  
  461.             /* if end of text then no match */
  462.             if ( !*t++ ) {
  463.                 return ABORT;
  464.             }
  465.         }
  466.  
  467.         /* move to next char in pattern */
  468.         p++;
  469.     }
  470.  
  471.     /* if end of pattern we have matched regardless of text left */
  472.     if ( !*p ) {
  473.         return TRUE;
  474.     }
  475.  
  476.     /* get the next character to match which must be a literal or '[' */
  477.     nextp = *p;
  478.     if ( nextp == '\\' )
  479.         nextp = p[1];
  480.  
  481.     /* Continue until we run out of text or definite result seen */
  482.     match = FALSE;
  483.     while ( match == FALSE ) {
  484.  
  485.         /* a precondition for matching is that the next character
  486.            in the pattern match the next character in the text or that
  487.            the next pattern char is the beginning of a range.  Increment
  488.            text pointer as we go here */
  489.         if ( nextp == *t || nextp == '[' ) {
  490.             match = regex_match(p, t);
  491.         }
  492.  
  493.         /* if the end of text is reached then no match */
  494.         if ( !*t++ ) match = ABORT;
  495.     }
  496.  
  497.     /* return result */
  498.     return match;
  499. }
  500.  
  501. /*----------------------------------------------------------------------------
  502. *
  503. * This is a shell to regex_match to return only a true BOOLEAN value
  504. *
  505. ----------------------------------------------------------------------------*/
  506.  
  507. BOOLEAN match( char *p, char *t)
  508. {
  509.     return ( regex_match(p,t) == TRUE ) ? TRUE : FALSE;
  510. }
  511.  
  512.  
  513. #ifdef TEST
  514.  
  515.     /*
  516.     * This test main expects as first arg the pattern and as second arg
  517.     * the match string.  Output is yaeh or nay on match.
  518.     */
  519.  
  520.     #include <stdio.h>
  521.  
  522.     int main(int argc, char *argv[])
  523.     {
  524.         if (argc == 3) {
  525.             if (is_pattern(argv[1])) {
  526.                 if (match(argv[1],argv[2])) {
  527.                     printf("    Match Successful\n");
  528.                 }
  529.                 else {
  530.                     printf("    Match Fails\n");
  531.                 }
  532.             }
  533.             else {
  534.                 printf("    Bad Pattern\n");
  535.             }
  536.         }
  537.         else printf("    Bad Breath\n");
  538.         return(0);
  539.     }
  540.  
  541. #endif
  542.  
  543. ==================== END of Listing ====================
  544. -- 
  545. John Kercheval -- 127 NW Bowdion Pl #105 -- Seattle, WA  98107-4960
  546. Home(Voice): (206) 547-4676  --------  Work (Voice): (206) 324-0350
  547.