加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式备忘录

发布时间:2020-12-14 01:57:01 所属栏目:百科 来源:网络整理
导读:// 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/
// 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: 这两天研究了一下正则表达式,备忘之 ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读