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

时间:2010-06-19 04:05:50

标签: c++ regex boost-regex

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

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

}

如何打印匹配的值?

1 个答案:

答案 0 :(得分: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);
  }    
}

修改:已修正开始,结束==&gt;第一,第二