Question

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;
}
Was it helpful?

Solution

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 becomes boost:: instead of std::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_search returns 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 "".

OTHER TIPS

Have you tried escaping the (). In some regexp implementations you must use \( for grouping. And anyways you probably don't need it.

The most basic regexp for this would be:

"[a-zA-Z]+day"

And you would get the results by result[0]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top