C++ 正则获取url中参数
生活随笔
收集整理的這篇文章主要介紹了
C++ 正则获取url中参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉自:http://www.cnblogs.com/wuhanqing/p/4575690.html
在訪問網頁過程中,為了識別所做操作或者訪問對象的編號,大多是用Get方式進行提交網頁。所以就有我們經常看到的url,比如http://longzhu.com/channels/speed?from=figameindex。
那么在url中的參數如何獲取呢,在ASP.NET中是通過 Request["from"] 獲取的,如果參數不存在或沒有該參數,則返回null,如果存在就可以將返回結果轉換成相應類型,然后進行相應處理。
作者最近在學習C++11中的正則表達式,所以想用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 CodeWebUrl類實現
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 // 匹配只有一個參數的url 13 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
總結
以上是生活随笔為你收集整理的C++ 正则获取url中参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: word 添加页眉页脚,添加不同页码
- 下一篇: °¬Èð×Éѯ¼¯ÍŸ߼¶¸±×Ü