// _Test_All.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <boost/regex.hpp>
#include <iostream>
using namespace std;
#include <conio.h>
/*------------------------------------------------------------------------------
/* [9/10/2011 Hjz]
/*
/*----------------------------------------------------------------------------*/
int _tmain(int argc, _TCHAR* argv[])
{
FILE* pFile = fopen( "test.txt", "r" );
if( ! pFile )
return 0;
char sz[ 1024 ] = { 0 };
fread( sz, sizeof( sz ), 1, pFile );
if( strlen( sz ) <= 0 )
return 0;
boost::cmatch mat;
boost::regex reg( "\\d+" ); //查找字符串里的数字
if( boost::regex_search( sz, mat, reg ) )
{
cout << "searched:" << mat[ 0 ] << endl;
}
{ //提取子串
boost::cmatch mat;
boost::regex reg( "\\d+" );
bool r=boost::regex_match( sz, mat, reg);
if(r) //如果匹配成功
{
//显示所有子串
for(boost::cmatch::iterator itr=mat.begin(); itr!=mat.end(); ++itr)
{
// 指向子串对应首位置 指向子串对应尾位置 子串内容
cout << itr->first-sz << ' ' << itr->second-sz << ' ' << *itr << endl;
}
}
//也可直接取指定位置信息
if(mat[4].matched) cout << "Path is" << mat[4] << endl;
}
{ //使用迭代器找出所有数字
boost::regex reg( "\\d+" ); //查找字符串里的数字
boost::cregex_iterator itrBegin( sz, sz + strlen( sz ), reg );
boost::cregex_iterator itrEnd;
cout << "-------------find number start-------------" << endl;
for(boost::cregex_iterator itr=itrBegin; itr!=itrEnd; ++itr)
{
// 指向子串对应首位置 指向子串对应尾位置 子串内容
cout << (*itr)[0].first-sz << ' ' << (*itr)[0].second-sz << ' ' << *itr << endl;
}
cout << "-------------find number end-------------" << endl;
}
{ //使用迭代器拆分字符串
boost::regex reg("/"); //按/符拆分字符串
boost::cregex_token_iterator itrBegin(sz, sz+strlen(sz), reg,-1);
boost::cregex_token_iterator itrEnd;
cout << "-------------token number start-------------" << endl;
for(boost::cregex_token_iterator itr=itrBegin; itr!=itrEnd; ++itr)
{
cout << *itr << endl;
}
cout << "-------------token number end-------------" << endl;
}
getch();
return 0;
}