首先我们看看一下代码:
/*******************************************************************************
# Author : Neo Fung
# Email : neosfung@gmail.com
# Last modified: 2011-11-16 16:30
# Filename: Boost xpressive正则表达式实验(测试).cpp
# Description :
******************************************************************************/
// Boost xpressive正则表达式实验(测试).cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <boost/xpressive/xpressive_dynamic.hpp>
#include <boost/xpressive/regex_primitives.hpp>
#include <string>
#include <locale.h>
#include <Windows.h>
using namespace std;
using namespace boost::xpressive;
string wstr2str(const wstring &wstr)
{
string result;
//获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
char* buffer = new char[len + 1];
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
//删除缓冲区并返回值
result.append(buffer);
delete[] buffer;
return result;
}
int main()
{
std::locale old_loc = std::locale::global(std::locale("CHS"));
wstring ws (_T("你好,。aaaa,./09357*&!@#$%^&*())_^%#"));
boost::xpressive::wsregex re=boost::xpressive::wsregex::compile(_T("[[:punct:]]"));
cout<<wstr2str(boost::xpressive::regex_replace(ws,re,_T("")))<<endl;
std::locale::global(old_loc);
return 0;
}
主要有3步:
1. 对于中文字符,我们必须要转换成宽字符才能处理。
2. 而如果要处理中文字符,我们还需要把区域设置为中国。
alnum | 任何字符数字 |
alpha | a-z和A-Z之间的字母。如果设置了地域的话,可能包含其它字符。 |
blank | 任何空白字符,空格或者tab字符。 |
cntrl | 任何控制字符 |
digit | 任何0-9之间的数字 |
graph | 任何图形字符 |
lower | a-z之间的小写字符。如果设置了地域的话,可能包含其它字符。 |
| 任何可打印字符 |
punct | 任何标点符号 |
space | 任何空格字符 |
upper | A-Z之间的大写字母。如果设置了地域的话,可能包含其它字符。 |
xdigit | 任何在0-9,a-f和A-F之间的16进制数字 |
word | 任何单词字符 – 字母数字加上下划线 |
Unicode | 任何编码大于255的字符,只能在宽字符中使用 |