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   
GeneralMany thanks, with 1 small gripe ..memberDavid Patrick29 Sep '04 - 8:41 

most C compare functions return zero when the values are equal, but this function returns non-zero.
 
Personally, I find the non-zero to be more intuitive .. but after years of forcing myself to check for zero I find it a bit counter-intuitive.
 
I think I'll just rename the function when I add it to my library Smile | :)
 
But that certainly wont stop me from using this wonderful routine.
 
Many sincere thanks ...
 

GeneralRe: Many thanks, with 1 small gripe ..memberJack Handy6 Oct '04 - 8:13 
David Patrick wrote:
most C compare functions return zero when the values are equal, but this function returns non-zero.
 
You make a good point. I probably should have made it behave like the strcmp() type functions. I'm a bit afraid to change it at this point since it has been posted for so long. It should be an easy fix for you or anyone else who is used to C style string comparisons. The C++ people here probably like the current behavior I would imagine.
 
-Jack
 

There are 10 types of people in this world, those that understand binary and those who don't.


GeneralRe: Many thanks, with 1 small gripe ..memberVic Mackey16 Oct '04 - 19:33 
I disagree. The return value for strcmp() is more than simply a test for equality, it tells you which string is greater than the other. A zero return value for strcmp() makes sense, but not for wildcmp() since the return value is strictly boolean, match or no match. The current implementation is fine (although some people might be picky about the return type, int vs bool). Perhaps to avoid confusion with string comparison functions, the function should be renamed to wildmatch() or something similar.

GeneralRe: Many thanks, with 1 small gripe ..memberVoja Intermajstor24 Nov '04 - 23:26 

You are completely right, Vic.
 
It is interesting that I have renamed the function in my code to wildmatch(). Wink | ;)
It would be a good new name.
 
Regards, Voja
GeneralNice code...membervoja2125 Aug '04 - 2:30 

This is realy nice & and useful code. I used to write something similar, but your example is simplier and shorter.
Because it lacks comments, I spent some time to understand (before I saw comment form Targys Hmmm | :| - real tutorial Wink | ;) ) and it is clear now. Thanks to both of you!
 
To 'wise' guys, flamers, and other people who has nothing to do instead of arguing:
- If the code has a bug, report but don't pretend you are a genius or a guru. If you can do it better, submit an article.
If you don't like the code, don't use it!
 
And about NULL pointers:
Idiot-proofing should be implemented at the level where data (function arguments) is acquired and prepared, not in such low-level function.
Besides that, I tested several functions from string.h with NULL parameters and every single one threw an exception. No further comments...
 
Regards, Voja
GeneralSlight efficiency improvementmemberBill Buklis9 Jul '04 - 6:53 

Great piece of code, but I have one minor improvement. It appears to me that the variable "cp" doesn't do anything and servers no purpose.
 
If I'm correct, then you can safely remove the line:
cp = string+1;
 
and also remove:
string = cp;
 
and replace:
cp = string++;
 
with:
++string;
 

I'm believe the results would be identical.

GeneralRe: Slight efficiency improvementmemberBill Buklis9 Jul '04 - 7:19 
Maybe I posted too soon. I didn't think there was a way for cp to not equal string+1. But, after thinking about it some more I found a pattern type that would:
 
*???c*
 
It's interesting how the loop keeps shifting back and forth with this type of pattern.
 
However, using a test string of "testing" with the above pattern the match still failed (correctly) using both algorithms. But, there easily may be a pattern and string combination that wouldn't work without cp.
QuestionPathMatchSpec (shlwapi.h)?memberpeterchen28 Jun '04 - 6:56 
Just a thought:
the PathMatchSpec SLWU API could provide similar. I guess it does have some differences (e.g. allowing to specify multiple specs, separated by semicolon), but it might be a simple alternative for many similar tasks.
 

 

we are here to help each other get through this thing, whatever it is Vonnegut jr.

sighist || Agile Programming | doxygen

AnswerRe: PathMatchSpec (shlwapi.h)?memberJack Handy13 Feb '05 - 9:56 
peterchen wrote:
Just a thought:
the PathMatchSpec SLWU API could provide similar. I guess it does have some differences (e.g. allowing to specify multiple specs, separated by semicolon), but it might be a simple alternative for many similar tasks.

 
The wildcmp() function is meant to be lightweight and fast.
 
If the extra functionality of multple specs is needed and you don't want to parse the input yourself then you can go ahead and use the PathMatchSpec() API.
 
Just make sure you don't mind these limitations:
 
1. Adding another dependancy to your executable by including the lib
2. Not portable (wildcmp() compiles fine under unix)
3. More memory overhead (larger code footprint)
4. The horrible slowness
 
I have ran some benchmarks and pasted the results below. I can provide the .cpp file for the benchmarks if anyone is interested.
 
-Jack
 
10MM iterations.
Compiled as a console app using vc6 in release mode with /O2 optimization.
Ran on a pM 1.7ghz
 
"C:\\T*s*.t?t", "C:\\Test\\File.txt"
PathMatchSpec MATCH => 20.5090s
wildcmp MATCH => 1.0320s
 
"C:\\T*s*.t??t", "C:\\Test\\File.txt"
PathMatchSpec NO MATCH => 45.7760s
wildcmp NO MATCH => 0.8910s

 

There are 10 types of people in this world, those that understand binary and those who don't.


GeneralDoesnt seem to work well..sussBikram Singh13 May '04 - 1:56 
Tried these wildcards, and they show different results in your code and in Windows Explorer's search command.
 
??x*
*so*
??so*
??so??
 
Lack of comments in the code also make it a bit difficult to understand. On the whole however, good job!

 

Bikram

GeneralRe: Doesnt seem to work well..memberJack Handy21 Jun '04 - 9:13 
The Windows Explorer search is not a straight wildcard match. It essentially adds *'s to either end of your input string so "b?r" matches "foobar.txt". I take a more literal approach. This function does not presume to be smarter than the caller. It is not only meant for files, it is also very useful for checking hostmasks for example.
 
If you think my function is producing bad results, can you paste an example of the string along with the wildcard?
 
Thanks,
 
Jack
 

There are 10 types of people in this world, those that understand binary and those who don't.


GeneralCase Insensitive wildcmpmemberTechiex16 Mar '04 - 9:36 
I want case insenstive wildcmp function. Could anyone help me?
GeneralRe: Case Insensitive wildcmpmemberNeville Franks16 Mar '04 - 9:52 
Simply wrap the code that compares charaters in toupper() calls.
 
eg.
    if ((toupper(*wild) != toupper(*string)) && (*wild != '?')) {

 
Neville Franks, Author of ED for Windows www.getsoft.com and coming soon: Surfulater www.surfulater.com
 

GeneralRe: Case Insensitive wildcmpmemberTechiex23 Mar '04 - 9:33 
toupper doesnt support char characters. You could optimize this code.
This code compares also multilingual characters
 


#include

#define BIT5 0x20

char buf[] = "this is ®Ñê test";
char *pbuf;

int lower(int ch);


int lower(int ch)
{
if ((ch==64)||(ch==91)||(ch==92)||(ch==93))
return ch &= ~(ch & BIT5);
return ch |= BIT5;
}

int wildcmp(char *wild, char *string) {
char *cp, *mp;

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;
}
 

int main() {

for (pbuf = &buf[0]; *pbuf; ++pbuf)
*pbuf= lower (*pbuf);

if (wildcmp("*®ñê*", buf)){
printf ("match : %s \n", buf);
} else {
printf ("not match: %s \n",buf);
}
}



GeneralRe: Case Insensitive wildcmpmemberDavidCrow23 Feb '05 - 2:24 
Techiex wrote:
toupper doesnt support char characters
 
Since when?
 
ASSERT('A' == toupper('a'));

 

"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow


GeneralRe: Case Insensitive wildcmpmemberVic Mackey23 Feb '05 - 8:00 
Be careful when using toupper(), some of the CRT variations of this function _only_ work when the input is known to be lowercase. For example, the return value is invalid for _toupper('A') and some implementations of toupper('A') as well...check the documentation.

GeneralRe: Case Insensitive wildcmpmemberDavidCrow23 Feb '05 - 8:22 
Vic Mackey wrote:
Be careful when using toupper(), some of the CRT variations of this function _only_ work when the input is known to be lowercase.
 
Which is why I specified toupper() instead of _toupper(). The latter is nothing but a #define directive that does no checking.
 
In any case, I was simply responding to Techiex's statement that "toupper doesnt support char characters."
 

"Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow


GeneralRe: Case Insensitive wildcmpmemberf_randy12 Jun '06 - 18:13 
Doesnt seems to work for me.
GeneralExcellent code!memberHans Dietrich16 Jul '03 - 19:40 
Very nice, compact, works great and is very fast. Thanks, Jack!
 
Best wishes,
Hans
Generalchecking for nullmemberJack Handy13 Mar '03 - 20:38 
I've seen a few people in these boards complain that I didn't check for null pointers in this function. This is a C function and the last time I checked, passing NULL to strcmp or any other C string function will segfault. I'm not saying this is great, and if you wanted to add a check for null, that would be fine. I just don't think that this is a 'bug' (if you can even call it that) worth flaming an otherwise great function.
 
-Jack
 

There are 10 types of people in this world, those that understand binary and those who don't.


GeneralRe: checking for nullsussAnonymous15 Mar '03 - 20:10 
I agree. This is not what I meant.
 
Efrat
GeneralRe: checking for nullmemberJack Handy18 Mar '03 - 13:25 
Yeah, I wasn't talking to you, you were respectful. I was talking to the people below in the 'too complicated' thread. Namely 'The C++ Guru'.
 
-Jack
 

There are 10 types of people in this world, those that understand binary and those who don't.


Generalgreat code, but ...sussAnonymous12 Mar '03 - 3:17 
great code, but if I'm not mistaken
cp can point beyon string array bounds.
try: wild="*a", string="xyzab"
 
correction:
string = cp++;
should be changed to:
string = cp;
if(*cp) cp++;
GeneralRe: great code, but ...memberJack Handy13 Mar '03 - 20:34 
I can not reproduce this bug.
 
wildcmp("*a", "xyzab") returns 0 as it should.
 
Can you elaborate on what you are doing to cause it to function incorrectly?
 
Thanks,
 
Jack
GeneralRe: great code, but ...sussAnonymous15 Mar '03 - 20:08 
You're right, it is not a bug in functionality,
but when I debugged it I saw that
for the above input, the line:
string = cp++;
causes cp to point one place beyond the string array bounds.
(When string points to the last char 'b', cp points to \0.
On the next iteration, string will be advanced to point to \0,
and cp will be advanced to point to one place after the \0).
Although it is not critical,I thought it is worth fixing.
 
regards,
Efrat

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