日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ 正则获取url中参数

發布時間:2023/12/14 c/c++ 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 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 // 匹配只有一個參數的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中参数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。