修复了一个小概率可能出现的bug,
就是文本“123*456”和表达式“123*6”不匹配的问题,*当作普通字符匹配用掉了,大材小用了
然后增加了2种匹配方式算法,
之前的算是完全匹配,要整个文本完全匹配完才返回真
局部匹配:从任意中间地方匹配到一段就返回真
高级匹配:添加支持^和$(正则中的),限定开头和结尾。^和$没有转义支持,出现在表达式中间的话,一定会返回假
高级匹配也是局部匹配,但是前面+^,后面+$就等同于完全匹配了
#include <cstdio>bool IsFullMatch(const char* pStr, const char* pPattern) { const char* pStarNext{},//星号后一位 * pStrNext{};//星号匹配完后一位 while (*pStr) { if (*pPattern == '*') {pStarNext = ++pPattern;pStrNext = pStr; } else if (*pPattern == '?' || *pPattern == *pStr) {++pStr;++pPattern; } else if (pStarNext) {//只要行不通了,就把上次的*号多塞一个字符pPattern = pStarNext;pStr = ++pStrNext; } else {return false; } } while (*pPattern == '*')++pPattern; return *pPattern == '\0';}bool IsSubMath(const char* pStr, const char* pPattern) { const char* pStarNext{ pPattern },//星号后一位 * pStrNext{ pStr };//星号匹配完后一位 while (*pStr) { if (*pPattern == '*') {pStarNext = ++pPattern;pStrNext = pStr; } else if (*pPattern == '?' || *pPattern == *pStr) {++pStr;++pPattern; } else if (*pPattern == '\0') {return true; } else {//只要行不通了,就把上次的*号多塞一个字符pPattern = pStarNext;pStr = ++pStrNext; } } while (*pPattern == '*')++pPattern; return *pPattern == '\0';}bool IsAdvMath(const char* pStr, const char* pPattern) {//支持^?*$ const char* pStarNext{ pPattern },//星号后一位 * pStrNext{ pStr };//星号匹配完后一位 if (*pPattern == '^') {//限定前面完全匹配 ++pPattern; pStarNext = pStrNext = nullptr; } while (*pStr) { if (*pPattern == '*') {pStarNext = ++pPattern;pStrNext = pStr; } else if (*pPattern == '?' || (*pPattern != '^' && *pPattern != '$' && *pPattern == *pStr)) {++pStr;++pPattern; } else if (*pPattern == '\0') {return true; } else if (pStarNext) {//只要行不通了,就把上次的*号多塞一个字符pPattern = pStarNext;pStr = ++pStrNext; } else {return false; } } while (*pPattern == '*')++pPattern; if (*pPattern == '$')++pPattern; return *pPattern == '\0';}int main() { const char* arr[][2] = { {"hello","h*o"},{"123","?2?"},{"abababakfd","a*ba*kfd"},{"aaa","a?b"}}; for (auto& e : arr) { printf("%d\n", IsFullMatch(e[0], e[1])); } getchar();}