Click here to Skip to main content
Click here to Skip to main content

Wildcard string compare (globbing)

By , 15 Feb 2005
 

Usage:

This is a fast, lightweight, and simple pattern matching function.

if (wildcmp("bl?h.*", "blah.jpg")) {
  //we have a match!
} else {
  //no match =(
}

Function:

int wildcmp(const char *wild, const char *string) {
  // Written by Jack Handy - <A href="mailto:jakkhandy@hotmail.com">jakkhandy@hotmail.com</A>
  const char *cp = NULL, *mp = NULL;

  while ((*string) && (*wild != '*')) {
    if ((*wild != *string) && (*wild != '?')) {
      return 0;
    }
    wild++;
    string++;
  }

  while (*string) {
    if (*wild == '*') {
      if (!*++wild) {
        return 1;
      }
      mp = wild;
      cp = string+1;
    } else if ((*wild == *string) || (*wild == '?')) {
      wild++;
      string++;
    } else {
      wild = mp;
      string = cp++;
    }
  }

  while (*wild == '*') {
    wild++;
  }
  return !*wild;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jack Handy
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDepends on whether you need to optimize the last few nanoseconds out of it...memberRenniePet29 Mar '10 - 7:45 
Hi Erwin,
 
Thanks for your posting. It did make me decide to investigate the situation.
 
I still really think this is a situation that begs for recursion. But maybe you were right that substring is not a good idea. So I made this version:
 
   public class MString2
   {
      /// <summary>
      /// Function to compare two strings, where strA may contain wildcard characters '*' and 
      /// '?'. http://en.wikipedia.org/wiki/Wildcard_character
      /// </summary>
      /// <param name="strA">string which may contain wildcards, may be empty, must not be null</param>
      /// <param name="strB">string to compare to, no wildcard processing, may be empty, must not be null</param>
      /// <param name="ignoreCase">true = ignore upper/lower case, false = don't ignore case</param>
      /// <returns>true = match, false = non-match</returns>
      public static bool CompareWWc(string strA, string strB, bool ignoreCase)
      {
         if (ignoreCase)
            return CompareWWc(strA.ToLower(), 0, strB.ToLower(), 0);
         else
            return CompareWWc(strA, 0, strB, 0);
      }
 

      /// <summary>
      /// Function to compare two strings, where strA may contain wildcard characters '*' and 
      /// '?'. http://en.wikipedia.org/wiki/Wildcard_character
      /// </summary>
      /// <param name="strA">string which may contain wildcards, may be empty, must not be null</param>
      /// <param name="strB">string to compare to, no wildcard processing, may be empty, must not be null</param>
      /// <returns>true = match, false = non-match</returns>
      public static bool CompareWWc(string strA, string strB)
      {
         // Just call the private recursive version of this function
         return CompareWWc(strA, 0, strB, 0);
      }
 

      /// <summary>
      /// Private recursive function used by the above two public functions.
      /// </summary>
      /// <param name="strA">string which may contain wildcards, may be empty, must not be null</param>
      /// <param name="indexA">index into strA marking start of the string for processing purposes</param>
      /// <param name="strB">string to compare to, no wildcard processing, may be empty, must not be null</param>
      /// <param name="indexB">index into strB marking start of the string for processing purposes</param>
      /// <returns>true = match, false = non-match</returns>
      private static bool CompareWWc(string strA, int indexA, string strB, int indexB)
      {
         // Top of loop to scan across strA (and strB)
         for (int i = 0; indexA + i < strA.Length; i++)
         {
            // Special processing when we hit a '*' in strA
            if (strA[indexA + i] == '*')
            {
               // If the '*' is at the end of strA then result = true irrespective of strB
               if (indexA + i == strA.Length - 1)
                  return true;
 
               // Do recursive calls to try to find a match somewhere to the right in strB
               for (int j = indexB + i; j < strB.Length; j++)
                  if (CompareWWc(strA, indexA + i + 1, strB, j))
                     return true;
               return false;
            }
 
            // Normal processing for non-'*' characters in strA
            if (indexB + i >= strB.Length || (strA[indexA + i] != strB[indexB + i] && strA[indexA + i] != '?'))
               return false;
         }
 
         // We've reached the end of strA and there is no '*' in strA
         return strA.Length - indexA == strB.Length - indexB;
      }
      
   }
 
Then I ran some timing tests, using System.Diagnostics.Stopwatch. I put my test case with 19 calls to the function in a loop and executed it 10,000 times. I did this for my original version, your version, and my new version. I compiled the programs in Release mode.
 
Assuming I haven't made a mistake somewhere, here are my results for a single function call:
 
My original version:  342 nonoseconds
Your version:         237 nanoseconds
My second version:    279 nanoseconds
Now to tell you the truth, I find it very difficult to get excited about saving 100 nanoseconds at the expense of having two and a half times as many lines of code. Especially since my expected use of this function in my application will probably never exceed a couple hundred calls per day. Smile | :)
 
Anyway, thanks for getting me to think things over again and make the tests. Personally, at least in this particular case, I prefer programmer understandability to execution efficiency. I've decided to stick with my original version, since I think my second version is more difficult to understand, and the improved efficiency not worth that disadvantage.
GeneralSorry - revised numbersmemberRenniePet29 Mar '10 - 8:35 
Hi Erwin,
 
Sorry - my previous numbers are not correct. I was running the programs under the Visual Studio debugger, and that was apparently not good for timing tests.
 
Here's what I get now:
 
My original version:  243 nonoseconds
Your version:          76 nanoseconds
My second version:    111 nanoseconds
Assuming these timings are valid, your version is three times faster than my original version, and that is pretty significant, at least in a situation were the function may be used millions times a day.
 
Sorry for the incorrect timings in my previous posting.
GeneralRe: Depends on whether you need to optimize the last few nanoseconds out of it...memberErwin de GRoot29 Mar '10 - 8:37 
Yes, the recursive function makes it more understandable for sure. In my case I actually call it several thousands of times after certain user actions, so I'm even considering using unsafe code Smile | :) I also thought of a special case where your function will get a performance hit: SearchString = "--ABC-----ABC-----ABC-----lots of text (without 'at') goes here", wildcardString = "*ABC*@". In this case my function (based on Jack's) will search for the '@' character once starting from position 5 (but won't find it, because it's not there). With your function it would search for the '@' character 3 times (once starting from position 5 until the end, once from 13 and once from 21). The longer the text at the end or the more occurances of 'ABC' at the start, the greater the performance hit.
GeneralYet another version - 25% faster, I think [modified]memberRenniePet1 Apr '10 - 8:24 
If at first you don't succeed...
 
Here's my third version, where I say to hell with minimizing lines of code and try to optimize the speed. No "unsafe" code though, unless you consider "goto" to be unsafe coding. Smile | :)
 
   public class MString
   {
      /// <summary>
      /// Compare two strings, where strA may contain wildcard characters '*' and '?'. 
      /// </summary>
      /// <param name="strA">string which may contain wildcards, may be empty, 
      ///                    must not be null</param>
      /// <param name="strB">string to compare to, no wildcard processing, may be empty, 
      ///                    must not be null</param>
      /// <param name="ignoreCase">true = ignore upper/lower case, false = observe case</param>
      /// <returns>true = match, false = non-match</returns>
      public static bool CompareWWc(string strA, string strB, bool ignoreCase)
      {
         if (ignoreCase)
            return CompareWWc(strA.ToLower(), strB.ToLower());
         else 
            return CompareWWc(strA, strB);
      }
 
      
      /// <summary>
      /// Compare two strings, where strA may contain wildcard characters '*' and '?'. 
      /// 
      /// In the comments, the word 'segment' is used to talk about the portions of strA that
      /// fall between two '*' characters, or between the start of the string and the first '*'
      /// or between the last '*' and the end of the string.
      /// </summary>
      /// <param name="strA">string which may contain wildcards, may be empty, 
      ///                    must not be null</param>
      /// <param name="strB">string to compare to, no wildcard processing, may be empty, 
      ///                    must not be null</param>
      /// <returns>true = match, false = non-match</returns>
      public static bool CompareWWc(string strA, string strB)
      {
         int starPtr = 0;  // Points at the '*' in strA

         // This part of the code handles the first segment in strA, or the case where strA
         //  does not contain any '*' character at all. The first segment is fairly simple to
         //  handle because it must match from the start of strB - no need to have a sliding 
         //  match loop.

         // Check strB long enough so we don't need to test for hitting its end while scanning
         if (strB.Length >= strA.Length)
         {
            // Simple optimized scan of first segment of strA and comparison with strB
            for (;; starPtr++)
            {
               if (starPtr == strA.Length)
                  return strA.Length == strB.Length;  // No '*' in strA and no mismatch
               if (strA[starPtr] == '*')
                  goto firstSegmentMatches;
               if (strA[starPtr] != strB[starPtr] && strA[starPtr] != '?')
                  return false;  // Mismatch
            }
         }
         else
         {
            // When strB is shorter than strA a match is not likely. But if strA contains 
            //  enough '*' characters it is possible, so we have to give it a try.
            for (;; starPtr++)
            {
               if (strA[starPtr] == '*')
                  goto firstSegmentMatches;
               if (starPtr == strB.Length)
                  return false;  // No '*' in strA before end of strB encountered
               if (strA[starPtr] != strB[starPtr] && strA[starPtr] != '?')
                  return false;  // Mismatch
            }
         }
 
         // The rest of the code handles the case where strA does contain one or more '*' 
         //  characters, and the first segment does match the start of strB.

      firstSegmentMatches:
 
         int indexA;  // Start of segment in strA
         int indexB = starPtr;  // Sliding match location in strB
         
         // Loop to process the segments in strA
         while (true)
         {
            // Test if next segment is last and empty
            indexA = ++starPtr;  // Point past '*'
            if (indexA == strA.Length)
               return true;  // Last segment empty - matches irrespective of strB content

            // Scan over the next segment in strA
            for (;; starPtr++)
               if (starPtr == strA.Length || strA[starPtr] == '*')
                  break;
 
            // Try to find match for this segment somewhere in strB
            for (;; indexB++)
            {
               if (starPtr - indexA > strB.Length - indexB)
                  return false;  // Mismatch if not enough characters left in strB

               for (int i = indexA, j = indexB; i < starPtr; i++, j++)
                  if (strA[i] != strB[j] && strA[i] != '?')
                     goto tryStringBAgain;
               
               goto findNextSegment;  // Match found for this segment in strB 

            tryStringBAgain:
               continue;
            }
 
            // Was that last segment? Return if so, loop if not.
         findNextSegment:
            indexB += starPtr - indexA;  // Point past matching portion of strB
            if (starPtr == strA.Length)
               return indexB == strB.Length;  // Return if that was last segment
         }
      }
 
   }
 
And here are my timing results (which I'm not totally sure of, I'm not used to timing code):
 
My original version:  243 nanoseconds    17 lines of code
Erwin's version:       76 nanoseconds    42 lines of code
My second version:    111 nanoseconds    16 lines of code
My third version:      56 nanoseconds    52 lines of code
 
I'd appreciate it if someone would check this out and let me know if they find any bugs or anything.
GeneralRe: Yet another version - 25% faster, I thinkmemberaleks1k21 Sep '11 - 2:47 
I found small bug, if compare "*a" and "babbba" function return false.
QuestionI used this function but I how I can catch variables from the * ???membermoh.hijjawi20 Oct '09 - 1:55 
Dear Jack,
Dear all,
 
I used this function in comparing two strings the first is Pattern(* KK *) and the second is Text(TT KK ZZ) and the function return pass. thats briliant,but my question how I can edit the function to be able to catch or handle the characters of matched * to save them in variables. for example:
 
X = TT
Y = ZZ
 
to deal with them later on in my system.
 
I tried many times but its not working well so far.
 
So please any one have an idea to do that please let me know and its will be appreciated.
 
Best Regards.
AnswerRe: I used this function but I how I can catch variables from the * ???memberRenniePet1 Apr '10 - 11:27 
It would be easiest if you use regular expressions instead of this function.
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection.aspx[^]
Questionany updates ?memberalhambra-eidos2 Jul '09 - 5:12 
code in C# ??
 
AE

GeneralImproved matching with end-of-textmemberAnders Heie11 May '09 - 15:20 
Great code, but when trying this I realized that the following pattern is a match:
 
Search: ????????
Text to search: ABC
 
The problem is that the pattern can be LONGER than the text searched, in which case it should return a not found, but instead returns found.
 
Also, this example succeeds:
 
Search: y*n
Text to search: yessir
 
But of course should fail, since I'm looking for a text that ends with n
 
So I re-wrote your program to this, to correctly handle this situation.
 
bool StrWildCmp(char* wildstring, char *matchstring){
 
	
	char stopstring[1];
	*stopstring = 0;
 
	while(*matchstring) {
		if (*wildstring == '*') {
		  if (!*++wildstring) {
			return true;
		  } else {
			  *stopstring = *wildstring;
		  }
		}
 
		if(*stopstring) {
			if(*stopstring == *matchstring ) {
				wildstring++;
				matchstring++;
				*stopstring = 0;
			} else {
				matchstring++;
			}
		} else if((*wildstring == *matchstring) || (*wildstring == '?')) {
				wildstring++;
				matchstring++;
		} else {
			return false;
		}
 
		if(!*matchstring && *wildstring && *wildstring != '*') {
			// matchstring too short
			return false;
		}
	}
 
  return true;
}
 
Thanks again for the inspiration. Cool | :cool:
GeneralRe: Improved matching with end-of-text: some cases don't work properly!memberroadrunner31412 Aug '09 - 3:35 
some cases don't work properly:
 
wildstring = "a*bc"
matchstring = "abbc"
should be true, but it returns false
 
wildstring = "a*b"
matchstring = "a"
should be false, but it returns true
 
wildstring = "a*?b"
matchstring = "axb"
should be true, but it returns false
 
wildstring = "a**b"
matchstring = "axb"
should be true, but it returns false (ok, the two ** aren't useful, but they should work)
 
I solved the last 3 bugs, but the first one is a bit tricky...
bool StrWildCmp(char* wildstring, char *matchstring){
   char stopstring[1];
   *stopstring = '\0';
 
   while(*matchstring != '\0')
   {
      if (*wildstring == '*') 
      {
         do
         {         
            wildstring++;            
         } while (*wildstring == '*');  // if a dork entered two or more * in a row 
                                        // ignore them and go ahead
         
         if (*wildstring == '\0')   // if * was the last char, the strings are equal
         {
            return TRUE;
         }
         else
         {
            *stopstring = *wildstring; // the next char to check after the *
         }
      }
 
      if(*stopstring != '\0')
      {
         if((*stopstring == *matchstring) || (*stopstring == '?') ) 
         {
            wildstring++;
            *stopstring = '\0';
         }
         matchstring++;
      }
      else
         if((*wildstring == *matchstring) || (*wildstring == '?'))
         {
            wildstring++;
            matchstring++;
         }
         else
         {
            return FALSE;
         }
 
      if( (*matchstring == '\0') && (*wildstring != '\0') )
      {
         // matchstring seems to be too short. Check if wildstring has any more chars except '*'
         while (*wildstring == '*') // ignore following '*'
            wildstring++;
         
         if (*wildstring == '\0') // if wildstring endet after '*', strings are equal
            return TRUE;
         else
            return FALSE;
      }
}

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 15 Feb 2005
Article Copyright 2001 by Jack Handy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid