rarbox
rarbox

Reputation: 486

How do I get the regex matched value using Boost.Regex?

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?

Upvotes: 3

Views: 6384

Answers (1)

jwismar
jwismar

Reputation: 12258

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

Upvotes: 8

Related Questions