C++获取URL中的参数值并修改
获取URL中的参数值
WebUrl.h文件
#pragma once
#ifndef WEB_URL_H_
#define WEB_URL_H_
#include <regex>
#include<string>
using namespace std;
namespace crystal {
class WebUrl {
public:
WebUrl(const string& url) :_url(url) {}
WebUrl(string&& url) :_url(move(url)) {}
string Request(const string& request) const;
private:
string _url;
};
}
#endif
WebUrl.cpp文件
#include "WebUrl.h"
namespace crystal {
string WebUrl::Request(const string& request) const {
smatch result;
if (regex_search(_url.cbegin(), _url.cend(), result, regex(request + "=(.*?)&"))) {
//匹配具有多个参数的url
//*? 重复任意次,但尽可能少重复
return result[1];
}
else if (regex_search(_url.cbegin(), _url.cend(), result, regex(request + "=(.*)"))) {
//匹配只有一个参数的url
return result[1];
}
else {
//不含参数或制定参数不存在
return string();
}
}
}
参考:https://blog.csdn.net/u014421422/article/details/121589144
修改url中参数的值
string m_replace(string strSrc, const string& oldStr, const string& newStr, int count = -1) {
string strRet = strSrc;
size_t pos = 0;
int l_count = 0;
if (-1 == count) {//replace all
count = strRet.size();
}
while ((pos = strRet.find(oldStr, pos)) != string::npos) {
strRet.replace(pos, oldStr.size(), newStr);
if (++l_count >= count) break;
pos += newStr.size();
}
return strRet;
}
参考:https://www.cnblogs.com/yuxuan-light-of-Taihu-Lake/p/15582474.html
在main中测试
#include <iostream>
#include "WebUrl.h"
using namespace std;
using namespace crystal;
int main(){
//获取参数
string url = "www.qqq.com/index.html?dateType=1&fileType=1&filePath=vfzs55&fileId=164&extension=7z&cardNo=111111111111111111&key=zapooi";
WebUrl web(url);
string oldNo = web.Request("cardNo");
string newNo = "888888888888888888";
//替换参数
string newURL = m_replace(url,cardNo,newNo);
cout << newURL << endl;//输出内容为:www.qqq.com/index.html?dateType=1&fileType=1&filePath=vfzs55&fileId=164&extension=7z&cardNo=888888888888888888&key=zapooi
}