3

I'm trying to extract the domain from a URL. Following is an example script.

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main () {

  std::string url = "http://mydomain.com/randompage.php";
  boost::regex exp("^https?://([^/]*?)/");
  std::cout << regex_search(url,exp);

}

How do I print the matched value?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
rarbox
  • 486
  • 5
  • 14

1 Answers1

8

You need to use the overload of regex_search that takes a match_results object. In your case:

#include <iostream>
#include <string>
#include <boost/regex.hpp>

int main () {    
  std::string url = "http://mydomain.com/randompage.php";
  boost::regex exp("^https?://([^/]*?)/");
  boost::smatch match;
  if (boost::regex_search(url, match, exp))
  {
    std::cout << std::string(match[1].first, match[1].second);
  }    
}

Edit: Corrected begin, end ==> first, second

jwismar
  • 12,164
  • 3
  • 32
  • 44
  • I'm getting errors when I compile this. main.cpp: In function ‘int main()’: main.cpp:11: error: ‘const struct boost::sub_match<__gnu_cxx::__normal_iterator, std::allocator > > >’ has no member named ‘begin’ main.cpp:11: error: ‘const struct boost::sub_match<__gnu_cxx::__normal_iterator, std::allocator > > >’ has no member named ‘end’ – rarbox Jun 19 '10 at 04:26
  • My fault. I'll fix it. It should be first and second, not begin() and end(). – jwismar Jun 19 '10 at 04:29