您的位置:首页 > 其它

字符串正则表达式匹配

2016-05-31 10:42 351 查看
题目:请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配。

bool match(char* str, char* pattern)
{
if(str==NULL && pattern==NULL)
return true;
if(str==NULL || pattern==NULL)
return false;
return matchCore(str,pattern);

}

bool matchCore(char *str,char *pattern)
{
if(*str=='\0' && *pattern=='\0')
return true;
if(*str!='\0' && *pattern=='\0')
return false;
//以当前字符的下一个字符是否为*作为分界,分别判断在当前字符是否匹配的情况下,应采取何种操作。
if(*(pattern+1)=='*')
{

if(*str==*pattern || (*pattern=='.'&&*str!='\0'))  //匹配
return matchCore(str+1,pattern+2)|| matchCore(str+1,pattern)|| matchCore(str,pattern+2); //不管当前字符是否匹配,
//matchCore(str,pattern+2)总可以是一种下一状态。
else
return matchCore(str,pattern+2);  //不匹配
}
//-----------------------------------------------------------------------------------------
if(*str==*pattern || (*str!='\0'&& *pattern=='.'))//匹配
return matchCore(str+1,pattern+1);
else
return false; //不匹配

}


注:这里主要考虑‘*’字符对匹配的影响。现当当前字符匹配时针对以下三种情况分析:
matchCore(str+1,pattern+2)
//字符串 aabc  模式串  aa*bc
matchCore(str+1,pattern)
//字符串 aaaabc  模式串  aa*bc (aaa*bc   aaaabc)     指针始终指向*前的第一个a的位置,一直处于当前状态



matchCore(str,pattern+2)
//字符串 aabc  模式串  aa*abc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: