C++ 正则获取url中参数

在访问网页过程中,为了识别所做操作或者访问对象的编号,大多是用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. 1 #include <iostream>

  2. 2 #include "WebUrl.h"

  3. 3 using namespace std;

  4. 4 using namespace crystal;

  5. 5

  6. 6 int main() {

  7. 7 try {

  8. 8 WebUrl web("www.123.com/index.aspx?catalog=sport&id=10&rank=20&hello=hello");

  9. 9 cout << web.Request("catalog") << endl;

  10. 10 cout << web.Request("id") << endl;

  11. 11 cout << web.Request("rank") << endl;

  12. 12 cout << web.Request("hello") << endl;

  13. 13 cout << web.Request("world") << endl;

  14. 14 } catch (const regex_error& e) {

  15. 15 cout << e.code() << endl;

  16. 16 cout << e.what() << endl;

  17. 17 }

  18. 18

  19. 19 return 0;

  20. 20 }

View Code

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

猜你喜欢

转载自blog.csdn.net/u014421422/article/details/121589144