Regex Iterators

These iterators are of type regex_iterator<> and have the usual instantiations for strings and character sequences with prefixes s, c, ws, or wc.

思考下面两点的功能:

  • smatch
  • str(), str(1), str(2)
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <string>
#include <regex>
#include <iostream>
#include <algorithm>
using namespace std;

void main()
{
	string data = "<person>\n"
		" <first>Nico</first>\n"
		" <last>Josuttis</last>\n"
		"</person>\n";
	// 
	regex reg("<(.*)>(.*)</(\\1)>");
	// 第1种代码
	// iterate over all matches (using a regex_iterator): 
	sregex_iterator pos(data.cbegin(), data.cend(), reg);
	// initialize a regex iterator, iterating over data to search for matches of reg
	sregex_iterator end;// default constructor of this type defines a past-the-end iterator
	for (; pos != end; ++pos) 
	{
		cout << "match:  " << pos->str() << endl;
		cout << " tag:   " << pos->str(1) << endl;
		cout << " value: " << pos->str(2) << endl;
	}
	cout << endl;

	// 第2种代码形式(完成相同功能)
	// 完成相同功能的另一种代码形式
	sregex_iterator beg(data.cbegin(), data.cend(), reg);
	sregex_iterator end;//
	// using Lambdas 和for_each算法
	for_each(beg, end, [](const smatch& m) {
		cout << "match:  " << m.str() << endl;
		cout << " tag:   " << m.str(1) << endl;
		cout << " value: " << m.str(2) << endl;
	});
	cin.get();
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值