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();
}