正则表达式备忘录

// 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("*"), string(".{0,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(), mingganci.length(), '*');
			 
			std::cout<<instr<<std::endl;
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	ForRegexTest2();

	return 0;
}


20140122: 这两天研究了一下正则表达式,备忘之 ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值