C++ 正则获取url中参数
来源:互联网 发布:濮阳招聘数控编程 编辑:程序博客网 时间:2024/06/06 21:06
转自: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 #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
0 0
- C++ 正则获取url中参数
- 正则表达式获取URL参数
- 正则表达式获取url参数
- 正则获取URL的参数
- 正则表达式获取url参数
- 在JavaScript中获取请求的URL参数[正则]
- 正则表达式获取url中的参数。
- url获取参数的正则表达式
- 解析url,获取参数,正则法
- jquery获取url参数 (正则)
- 正则表达式获取url中的参数
- JS使用正则表达式获取URL参数
- freemark中获取URL参数
- url中获取参数值
- JS-获取Url中参数
- react获取URL中参数
- 实例学正则表达式之三 -- 如何获取URL的中参数值
- 在MFC程序中,利用boost 正则表达式获取URL参数示例
- 如何用微信支付宽带费用、wifi网费
- caffe基础介绍
- 第十一周时间项目(5)——d
- HQL总结
- ORACLE中Like与Instr模糊查询性能大比拼
- C++ 正则获取url中参数
- ajax进行跨域操作
- 如何debug自定义AbstractProcessor
- 微信公众号开发--会员免登录操作
- lsof 一切皆文件
- android中Paint类参数介绍
- 文字区域
- Java内存模型
- 深入Objective-C的动态特性