標籤:
在訪問網頁過程中,為了識別所做操作或者訪問對象的編號,大多是用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 #endifView 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中參數