雨光

rayrain

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

不想多说,非常经典的文件通配符模式匹配函数,不想用正则表达式的理想选择。来源已记不清楚。
使用示例:if (IsMatch("C:Windows\exp.tmp", "*.tmp")) ...
 
#if _UNICODE
    typedef wchar_t tchar;
#else
    typedef 
char tchar;
#endif

bool IsMatch(const tchar* source, const tchar* filter)
{
    
if(source == NULL || filter == NULL)
    {
        
return FALSE;
    }

    
const tchar* cp = NULL;
    
const tchar* mp = NULL;
    
while((*source) && (*filter != '*'))
    {
        
if ((*filter != *source) && (*filter != '?')) return FALSE;
        filter
++;
        source
++;
    }

    
while (*source) 
    {
        
if (*filter == '*'
        {
            
if (!*++filter) return TRUE;
            mp 
= filter;
            cp 
= source + 1;
        } 
        
else if ((*filter == *source) || (*filter == '?')) 
        {
            filter
++;
            source
++;
        }
        
else 
        {
            filter 
= mp;
            source 
= cp++;
        }
    }

    
while (*filter == '*'
    {
        filter
++;
    }

    
return !*filter;
}

 

 

posted on 2010-01-17 16:27  rayrain  阅读(303)  评论(0编辑  收藏  举报