C++ 正則擷取url中參數

來源:互聯網
上載者:User

標籤:

    在訪問網頁過程中,為了識別所做操作或者訪問對象的編號,大多是用Get方式進行提交網頁。所以就有我們經常看到的url,比如http://longzhu.com/channels/speed?from=figameindex。

    那麼在url中的參數如何擷取呢,在ASP.NET中是通過 Request["from"] 擷取的,如果參數不存在或沒有該參數,則返回null,如果存在就可以將返回結果轉換成相應類型,然後進行相應處理。

    作者最近在學習C++11中的Regex,所以想用C++中的正則,實現相應功能。下面貼上代碼。

 

    WebUrl類定義

 1 #ifndef WEB_URL_H_ 2 #define WEB_URL_H_ 3  4 #include <regex> 5 #include <string> 6 using namespace std; 7  8 namespace crystal { 9     class WebUrl {10     public:11         WebUrl(const string& url) : _url(url) {}12         WebUrl(string&& url) : _url(move(url)) {}13 14         string Request(const string& request) const;15     private:16         string _url;17     };18 }19 20 #endif
View Code

    WebUrl類實現

 1 #include "WebUrl.h" 2  3 namespace crystal { 4     string WebUrl::Request(const string& request) const { 5         smatch result; 6         if (regex_search(_url.cbegin(), _url.cend(), result, regex(request + "=(.*?)&"))) { 7             // 匹配具有多個參數的url 8  9             // *? 重複任意次,但儘可能少重複  10             return result[1];11         } else if (regex_search(_url.cbegin(), _url.cend(), result, regex(request + "=(.*)"))) {12             // 匹配只有一個參數的url13 14             return result[1];15         } else {16             // 不含參數或制定參數不存在17 18             return string();19         }20     }21 }
View Code

    測試代碼

 1 #include <iostream> 2 #include "WebUrl.h" 3 using namespace std; 4 using namespace crystal; 5  6 int main() { 7     try { 8         WebUrl web("www.123.com/index.aspx?catalog=sport&id=10&rank=20&hello=hello"); 9         cout << web.Request("catalog") << endl;10         cout << web.Request("id") << endl;11         cout << web.Request("rank") << endl;12         cout << web.Request("hello") << endl;13         cout << web.Request("world") << endl;14     } catch (const regex_error& e) {15         cout << e.code() << endl;16         cout << e.what() << endl;17     }18 19     return 0;20 }
View Code

 

參考:http://bbs.csdn.net/topics/320034235

轉載請註明出處 http://www.cnblogs.com/wuhanqing/p/4575690.html

by crystal

 

C++ 正則擷取url中參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.