关于boost的regex库和xpressive库匹配所有标点(含中文标点)的方法

首先我们看看一下代码:


/*******************************************************************************
 # 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. 而如果要处理中文字符,我们还需要把区域设置为中国。

3. [[:punct:]]指代的是任何标点,如果区域设置为中国后也包含中文标点。要使用[[:punct:]]必须包含头文件regex_primitives.hpp。[[:punct:]]代表正则表达式中的\p{punct}。 字符类是使用 “[:classname:]” 语法声明的集合。例如 “[[:space:]]” 是所有空白字符的集合。可用的字符类有:

 

alnum

任何字符数字

alpha

a-z和A-Z之间的字母。如果设置了地域的话,可能包含其它字符。

blank

任何空白字符,空格或者tab字符。

cntrl

任何控制字符

digit

任何0-9之间的数字

graph

任何图形字符

lower

a-z之间的小写字符。如果设置了地域的话,可能包含其它字符。

print

任何可打印字符

punct

任何标点符号

space

任何空格字符

upper

A-Z之间的大写字母。如果设置了地域的话,可能包含其它字符。

xdigit

任何在0-9,a-f和A-F之间的16进制数字

word

任何单词字符 – 字母数字加上下划线

Unicode

任何编码大于255的字符,只能在宽字符中使用

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值