在我们编程过程中,经常需要遇到字符串和指定的模板匹配,需要返回是否匹配字符串模板。
其中符号:%匹配任意多个字节,?匹配单个字符
模板形式举例如下:
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;
}