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

标签 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);

}

如何打印匹配的值?

最佳答案

您需要使用带有 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);
  }    
}

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

关于c++ - 如何使用 Boost.Regex 获取正则表达式匹配值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3074290/

相关文章:

c++ - 使用 unique_ptr 作为值初始化 const static std::map

c++ - 从函数中抛出内部对象异常是否合法

regex - 其他记录之间的字符串列表加载错误Hive

c++ - 如何使用boost C++解析8位十六进制数和字符串?

c++ - C++ 中的正则表达式

c++ - 如何在 C++ 中创建包含从 0 到 N 的元素的行 vector ?

c++ - 如何在用户在运行时输入任何内容时停止计时器

regex - 为什么标点符号的 R gsub(或正则表达式)没有得到所有标点符号?

java - 正则表达式编号

c++ - Boost regex_replace 异常 : "...This exception is thrown to prevent "eternal"matches. .."偶尔抛出