views:

25

answers:

1

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?

+1  A: 

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
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<const char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ has no member named ‘begin’main.cpp:11: error: ‘const struct boost::sub_match<__gnu_cxx::__normal_iterator<const char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ has no member named ‘end’
rarbox
My fault. I'll fix it. It should be first and second, not begin() and end().
jwismar
Thanks, that worked!
rarbox