开发者

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

开发者 https://www.devze.com 2023-01-03 20:07 出处:网络
I\'m trying to extract the domain from a URL. Following is an example script. #include <iostream>

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("开发者_JAVA百科^https?://([^/]*?)/");
  std::cout << regex_search(url,exp);

}

How do I print the matched value?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消