c++使用 boost 正则表达式匹配的 URL 解析器

发布于 2024-09-16 19:49:57 字数 221 浏览 2 评论 0原文

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

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

我需要拆分基本网址www.google.com,然后查询路径search?h=test&q=examaple

how can i parse an url in c++ with boost regex
like i have an url

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

i need to split the base url www.google.com and then query path search?h=test&q=examaple

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光与爱终年不遇 2024-09-23 19:49:57

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

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

Are you sure you need regex for that?

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

regex version:

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 );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文