华为编程大赛---含有通配符的字符串匹配问题---基于正则表达式

 问题描述
判断包含通配符的匹配字符串是否完全匹配输入的字符串,匹配字符串中包含的通配符仅有‘ * ’和‘?’,且通配符不会连续出现 。(要求完全匹配,而不是包含)
其中,通配符‘ * ’:代替 0 个或多个字符,通配符‘ ? ’:代替一个字符
 要求实现函数
int GetMatchSta (const char *ArrStr, const char *KeyStr)
【输入】 ArrStr :    给定的字符串
         KeyStr :       包含通配符的匹配字符串
【输出】 无
【返回】是否匹配,匹配返回1 ,不匹配返回0
l  示例
输入: ” abcdefg”, “a*”
返回: 1
 
输入: “tommababcabc” , t?m*ab*abc

返回: 1

参考了《代码之美》第一章---正则表达式匹配器 :http://blog.chinaunix.net/uid-26822401-id-3150018.html

#include <iostream>
#include <cstring>
using namespace std;
int GetMatchSta (const char *ArrStr,const  char *KeyStr);
int matchhere(const char *arrstr,const char *keystr);
int matchstar(const char *arrstr,char ch,const char *keystr);//处理 * 的情况 
int main()
{
	char *arr="tommababcabc";
	char *key="t?m*ab*abc";
	cout<<GetMatchSta(arr,key)<<endl; 
} 
int GetMatchSta (const char *ArrStr,const char *KeyStr)
{
	if(KeyStr[0]=='*' && KeyStr[1]!='\0' && KeyStr[1]!='?')
		return matchstar(ArrStr,KeyStr[1],KeyStr+1);
	if(KeyStr[0]=='*' && (KeyStr[1]=='?'))// "*?" 这种情况匹配所有除非源串为空 
		return strlen(ArrStr)!=0;
	if(KeyStr[0]=='*' && KeyStr[1]=='\0') // "*" 这情况匹配所有,包括空串 
		return 1;
	if(KeyStr[0]=='?')
		return matchhere(ArrStr+1,KeyStr+1);
	return matchhere(ArrStr,KeyStr);	 
}
int matchhere(const char *arrstr,const char *keystr)
{
	if(keystr[0]=='\0')
		return *arrstr=='\0';
	if(keystr[0]=='*')
		return matchstar(arrstr,keystr[1],keystr+1);
	if(*arrstr!='\0' && (keystr[0]==arrstr[0] || keystr[0]=='?'))
		return matchhere(arrstr+1,keystr+1);
	return 0;		
}
int matchstar(const char *arrstr,char ch,const char *keystr)
{
	if(ch=='\0') return 1;   //以 * 结尾 
	do{
		if(matchhere(arrstr,keystr))
			return 1;
	} while( *arrstr++ !='\0');
	return 0;
	
}


你可能感兴趣的:(编程,正则表达式,字符串匹配,华为)