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

raj*_*esh 3 c++ url boost boost-regex

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

http://www.google.co.in/search?h=test&q=examaple
Run Code Online (Sandbox Code Playgroud)

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

Kir*_*sky 6

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

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

正则表达式版本:

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