匹配一个字符串buf中,连续包换运算符reg的次数:
#include <iostream>//return 返回匹配的字符个数
//buf, 要检测的字符串
//reg, 包含的连续运算符
int GetMatchCount(std::string& buf, std::string& reg)
{int nMatchCount = 0;if (reg.empty())return nMatchCount;std::string matchReg = reg;for (int i = 0; i < buf.length(); i++){if (buf[i] == matchReg.front()){matchReg.erase(matchReg.begin());}if (matchReg.empty()){nMatchCount ++;matchReg = reg;}}return nMatchCount;
}
使用示例:
int main()
{std::string text = "[][][[(Hello World!)]";std::string reg = "[]";std::cout << "match string:\"" << text << "\" | reg(\"" << reg << "\")" << std::endl;int count = GetMatchCount(text, reg);std::cout << "match count: " << count << std::endl;return 0;
}
运行结果: