字符串模糊匹配-根据通配符%?

在我们编程过程中,经常需要遇到字符串和指定的模板匹配,需要返回是否匹配字符串模板。

 

 其中符号:%匹配任意多个字节,?匹配单个字符

模板形式举例如下:

1、  010%、010????????,用于判断电话号码是否是010开头。

2、 %民主%, 用于判断文本中是否含有敏感词。

3、%银行%信用卡% , 用于判断文本中是否含有特殊的语义。

       我们需要用文本:   "中国银行提供信用卡服务"  匹配 "%银行%信用卡%"

 下面的函数是作者编写整理的代码:

  其中参数:sKey 代表需要匹配的文本,例如:  中国银行提供信用卡服务   

                     sRule 代表文本要匹配的模板,例如:  %银行%信用卡%  

返回值:true,代表文本匹配模板,false,代表文本不匹配模板。

                调用举例: 

              bool   bMatchFlag;

            bMatchFlag = FuzzyMatch("中国银行提供信用卡服务", "%银行%信用卡%");

 


bool FuzzyMatch(char* sKey, char* sRule)
{
    int nKeyLen;
    nKeyLen = strlen(sKey);


    if(sRule[0] == sKey[0])
    {
        if(nKeyLen > 1)
        {
            return(FuzzyMatch(sKey+1, sRule+1));            
        }
        else if(nKeyLen == 1)
        {    
            sRule++;
            while(sRule[0] != '\0')
            {
                if(sRule[0] != '%')
                {
                    return false;
                }
                sRule++;
            }
            
            return true;
        }
    }  

    if(sRule[0] == '?')
    {
        if(nKeyLen > 1)
        {  
            sRule++;
            if(FuzzyMatch(sKey+1, sRule) == true)        
            {   
                return true;
            }
        }
        else if(nKeyLen == 1)
        {    
            if(strlen(sRule) == 1)
            {
                return true;
            }
            else 
            {                
                sRule++;
                while(sRule[0] != '\0')
                {    
                    if(sRule[0] != '%')
                    {
                        return false;
                    }
                    sRule++;
                }
                
                return true;
            }
        }
    }
    if(sRule[0] == '%')
    {
        int tmplen;
        char* sTemp;
        
        sTemp = sKey;
        tmplen = nKeyLen;
        
        if(sRule[1] != '\0')
        {   
            sRule++;
            while(tmplen > 0)
            {
                if(tmplen >= 1 )
                {                    
                    if(FuzzyMatch(sTemp, sRule) == true)
                    {
                        return true;           
                    }
                }
            
                sTemp++;
                tmplen = strlen(sTemp);
            }
        }        
        else
        {    
            return true;
        }
    }
    
    return false;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值