Reputation: 2250
I just want to fetch results of a given string
#include <regex>
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main () {
std::tr1::cmatch res;
string str;
str = "a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too";
std::tr1::regex rx("Test(\d+) (\\d+)");
std::tr1::regex_search(str.c_str(), res, rx);
std::cout << "RES 1: " << res[1] << ". " << res[2] << "\n";
std::cout << "RES 2: " << res[3] << ". " << res[4] << "\n";
return 0;
}
I want it to be able to get from one search the results of both, example:
Array 1: [1] = 2, [2] = 12 and Array 2: [1] = 3, [2] = 45 or it could be like this: [1] = 2, [2] = 12, [3] = 3, [4] = 45
how do I do that? If I'm using the incorrect function, tell me which function and how to use it to do what I asked here. I hope I was clear enough, Thanks in advance.
Upvotes: 2
Views: 694
Reputation: 541
What you're looking for is regex_iterator class template. In your example:
#include <regex>
#include <iostream>
#include <string>
int main () {
std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too");
std::tr1::regex rx("Test(\\d+) (\\d+)");
std::tr1::sregex_iterator first(str.begin(), str.end(), rx);
std::tr1::sregex_iterator last;
for (auto it = first; it != last; ++it)
{
std::cout << "[1]=" << it->str(1) << " [2]=" << it->str(2) << std::endl;
}
return 0;
}
Also, you can implement your option number 2 with regex_token_iterator class template:
#include <regex>
#include <iostream>
#include <string>
int main ()
{
std::string str("a lot of unknown text here<h2>Test2 12</h2> a lot of unknown text here <h2>Test3 45</h2>a lot of text here too");
std::tr1::regex rx("Test(\\d+) (\\d+)");
int fields[2] = { 1, 2 };
std::tr1::sregex_token_iterator first(str.begin(), str.end(), rx, fields);
std::tr1::sregex_token_iterator last;
std::size_t i = 0;
for (auto it = first; it != last; ++it)
{
std::cout << "[" << i << "]=" << it->str() << std::endl;
++i;
}
return 0;
}
Upvotes: 2