C++ - 正则表达式(regex) 迭代器(iterator) 的 详解 及 代码

正则表达式(regex) 迭代器(iterator) 的 详解 及 代码

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/17319899

 

正则表达式(regex), 使用boost的regex头文件, 是C++11的新标准, 但是gcc4.8.1并未完全支持, 所以使用boost库;

具体安装: http://blog.csdn.net/caroline_wendy/article/details/17282187

 

正则表达式的书写规范, 以ECMAScript为例, 使用迭代器可以遍历原字符串, 输出符合要求的所有字符串;

使用prefix()suffix()方法, 可以输出前一个未匹配的字符串和后一个未匹配的字符串;

正则表达式的子表达式(subexpressions), 可以分段输出正则表达式, 在正则表达式中, 以括号"()"分解;

 

代码如下:

 

#include <iostream>
#include <string>
#include <algorithm>
#include <boost/regex.hpp>

using namespace std;
using namespace boost;

int main()
{
	std::string pattern("[^c]ei");
	pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
	boost::regex r(pattern, regex::icase); //忽略大小写
	std::string str("Ruby Carolinei biubiubiu Weindy SpikeI Winnceiy");
	//使用正则迭代器进行遍历
	for(boost::sregex_iterator it(str.begin(), str.end(), r), end_it;
			it!=end_it; ++it)
		std::cout << it->str() << std::endl;

	//输出正则表达式的前后字符串
	std::cout << std::endl;
	for(boost::sregex_iterator it(str.begin(), str.end(), r), end_it;
			it!=end_it; ++it){
		auto pos = it->prefix().length();
		pos = pos>40 ? pos-40 : 0;
		std::cout << it->prefix().str().substr(pos) /*输出前一个未匹配的字符串*/
				<< "\n\t\t>>>" << it->str() << "<<<\n"
				<< it->suffix().str().substr(0, 40) /*输出之后的字符串*/
				<<std::endl;
	}

	//匹配子表达式
	std::string filename("File.cqp MyGod.cpP");
	boost::regex rsub("([[:alnum:]]+)\\.(cpp|cxx|cc)$", regex::icase);
	smatch results;
	if(boost::regex_search(filename, results, rsub))
		std::cout << results.str(1) << std::endl;
}


输出:

 

 

Carolinei
Weindy
SpikeI

Ruby 
		>>>Carolinei<<<
 biubiubiu Weindy SpikeI Winnceiy
 biubiubiu 
		>>>Weindy<<<
 SpikeI Winnceiy
 
		>>>SpikeI<<<
 Winnceiy
MyGod

 

 

 

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SpikeKing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值