// boost_regex_test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #pragma comment(lib,"libboost_regex-vc90-mt-gd-1_43.lib") #include "boost/regex/v4/regex.hpp" #include <iostream> #include <string> #include "boost/regex/v4/match_results.hpp" #include "boost/regex/v4/regex_split.hpp" //#include "" using namespace std; void xxxx() { boost::regex reg("(new)|(delete)"); boost::smatch m; // boost::match_results mrs; std::string s= "Calls to new must be (delete delete) followed by delete. / Calling simply new results in a leak!"; if (boost::regex_search(s,m,reg)) { // Did new match? if (m[1].matched) std::cout << "The expression (new) matched!/n"; if (m[2].matched) std::cout << "The expression (delete) matched!/n"; } } //替换字符串函数 void string_replace( std::string &strBig,const std::string &strsrc,const std::string &strdst ) { std::string::size_type pos = 0; std::string::size_type srclen = strsrc.size(); std::string::size_type dstlen = strdst.size(); while( (pos=strBig.find(strsrc,pos)) != std::string::npos ) { strBig.replace( pos,srclen,strdst ); pos += dstlen; } } void ForRegexTest2() { //?和*给非程序人员定义的通配符 std::string iniStr("s?h?i?t*on y*o*u"); std::string exprEvaluatedFromIniStr(iniStr); //在这里把通配符替换成正则表达式语法 string_replace(exprEvaluatedFromIniStr,string("?"),string(".{0,6}")); string_replace(exprEvaluatedFromIniStr,string("*"),1}")); boost::regex expression(exprEvaluatedFromIniStr,boost::regex::perl | boost::regex::icase); boost::smatch what; std::string instr("xx dfd sxh i~t hahahahah shit on y o u"); if (boost::regex_search(instr,what,expression)) { size_t tmpSize = what.size(); for (size_t i = 0; i < what.size(); ++i) { cout<< "Match String: " << what[i].str() << endl; cout << "Match Position: " << what.position(i) << endl; cout << "matchResults prefix: " << what.prefix() << endl; cout << "matchResults suffix: " << what.suffix() << endl; cout << "After first found string: " << instr.substr(what.position(i) + what.length(i)) << endl; std::string mingganci(what[i]); size_t foundPos = instr.find(mingganci); instr.replace(foundPos,mingganci.length(),'*'); std::cout<<instr<<std::endl; } } } int _tmain(int argc,_TCHAR* argv[]) { ForRegexTest2(); return 0; }
20140122: 这两天研究了一下正则表达式,备忘之 ...
原文链接:https://www.f2er.com/regex/362142.html