c++ Url Parser使用boost正则表达式匹配

标签 c++ url boost boost-regex

我如何使用 boost regex 解析 C++ 中的 url 就像我有一个 url

http://www.google.co.in/search?h=test&q=examaple

我需要拆分 base url www.google.com 然后查询路径 search?h=test&q=examaple

最佳答案

你确定你需要正则表达式吗?

#include <iostream>
#include <algorithm>

int main()
{
  using namespace std;
  string x = "http://www.google.co.in/search/search/?h=test&q=examaple";

  size_t sp = x.find_first_of( '/', 7 /* skip http:// part */ );
  if ( sp != string::npos ) {
        string base_url( x.begin()+7, x.begin()+sp );
        cout << base_url << endl;
        sp = x.find_last_of( '/' );
        if ( sp != string::npos ) {
                string query( x.begin()+sp+1, x.end() );
                cout << query << endl;
        }
  }

  return 0;
}

正则表达式版本:

string input_string = "http://www.google.co.in/search/search/?h=test&q=examaple";
boost::regex exrp( "^(?:http://)?([^/]+)(?:/?.*/?)/(.*)$" );
boost::match_results<string::const_iterator> what;
if( regex_search( input_string, what, exrp ) ) {
    std::string base_url( what[1].first, what[1].second );
    std::string query( what[2].first, what[2].second );
}

关于c++ Url Parser使用boost正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3624651/

相关文章:

c++ - 使用 ITK 写入图像

php - 通过单击链接在 cookie 中设置语言设置

c++ - Boost::geometry 查询返回索引

c++ - 我们可以连接 QPushButton 来改变 QSlider 的值吗?

c++ - 在构造函数C++中初始化属性时出现问题

url - bit.ly 和tinurl 等URL 缩短服务的商业模式是什么?

php - HTACCESS 友好 url 并允许 GET 方法

c++ - 使用 Boost C++ 库将正则表达式替换为自定义替换

python - 创建 boost-python 嵌套命名空间

c++ - 3D 场景文件格式和查看器