Any idea why the following code prints “no match“? Something related with the compiler or the version of the library? I compiled with g++ a.cpp.
#include <tr1/regex>
#include <iostream>
#include <string>
using namespace std;
int main()
{
const std::tr1::regex pattern("(\\w+day)");
std::string weekend = "Saturday and Sunday";
std::tr1::smatch result;
bool match = std::tr1::regex_search(weekend, result, pattern);
if(match)
{
for(size_t i = 1; i < result.size(); ++i)
{
std::cout << result[i] << std::endl;
}
}else
std::cout << "no match" << std::endl;
return 0;
}
Definitely an issue with your compiler. I would recommend (since you’re on Linux and that makes it particularly easy) to simply swap out
<tr1/regex>for<boost/regex.hpp>. The namespace also becomesboost::instead ofstd::tr1::but all other syntax is exactly the same and it may solve all your problems.If you can’t use boost, that’s a whole different story; but as of the past year or so, most people/employers/companies have been much more boost-friendly.
Also note that your test case is flawed. You have a loop, but it’ll only ever print a single value.
regex_searchreturns a value at a time, you need to keep calling it with the new search start index to get all results. If you said the output of the program was nothing (vs “no match”), then I would say the bug was in your code. But the code as it is currently written should return"Saturday"or"".