C++通配符模糊匹配

'?'可匹配任意单个字符.

'*'可匹配任意字符,包括空.

例如:

s: abc    p: a?c      ->匹配成功

s: abc    p: a*      ->匹配成功

实现基本逻辑是从左至右依次匹配,匹配到'*'时,更新cache,将*依次扩展字符进行匹配。

#include<iostream>
#include <fstream>
#include<string>

static bool isMatch(const char *sStr, const char *pStr);

int main()
{
	char source[] = "abcd";
	char part[] = "a**d";
	bool match = isMatch(source, part);
	std::cout << match<< std::endl;
	system("pause");
}

static bool isMatch
(
const char *sStr,  /* I: Source string */
const char *pStr   /* I: pattern string */
)
/*
DESCRIPTION:
	Check whether the pattern string matches the source string.

RETURN:
	Return 1 if match, else 0.
*/
{
	int cache[2] = { -1, -1 };
	int sPos = 0, pPos = 0;

	while (sPos < strlen(sStr))
	{
		if (pPos < strlen(pStr) && (pStr[pPos] == sStr[sPos]) ||
            pStr[pPos] == '?' || pStr[pPos] == '*')
		{
			if (pStr[pPos] == '*')
			{
				cache[0] = pPos;
				cache[1] = sPos;
			}
			else
			{
				sPos++;
			}

			pPos++;
		}
		else if (cache[0] != -1)
		{
			pPos = cache[0] + 1;
			sPos = cache[1] + 1;
			cache[1]++;
		}
		else
			return false;
	}

	/* such as "a", "a*" condition */
	while (pPos < strlen(pStr) && pStr[pPos] == '*')
		pPos++;
	
	return (pPos == strlen(pStr));
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值