如何使用Boost.Regex获取正则表达式匹配值?

rar*_*box 3 c++ regex boost-regex

我正在尝试从URL中提取域名.以下是一个示例脚本.

#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);

}
Run Code Online (Sandbox Code Playgroud)

如何打印匹配值?

jwi*_*mar 6

您需要使用带有match_results对象的regex_search的重载.在你的情况下:

#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);
  }    
}
Run Code Online (Sandbox Code Playgroud)

编辑:更正开始,结束==>第一,第二