C++从html代码中获取链接
C++ get a link from html code
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <regex>
using namespace std;
int main(int argc, char* argv[]) {
string test = "<html><div><script>var link = "http://example.com/?key=dynamic_key";</script></div></html>";
regex re("http://example.com/(*)");
smatch match;
if (regex_search(test, match, re)) {
cout<<"OK"<<endl;
}
return 0;
}
用于此编译的命令。
root# g++ test.cpp -o test -std=gnu++11
此程序不起作用。如何从html代码中获取链接(使用regex(?请帮帮我。
您的字符串构造不正确,请参阅"
转义:
string test = "<html><div><script>var link = "http://example.com/?key=dynamic_key";</script></div></html>";
我会使用这个正则表达式:
http://example.com[^"]*
只选择这个:
http://example.com/?key=dynamic_key
我发现您的代码有两个问题。
第一种方法是尝试将引号"
放在引号内而不进行转义。
你需要做:"escape your "quotes" properly"
(注意"
(:
此外,您的正则表达式也不太正确,*
需要跟随一个可匹配的字符(如[^"]
,意思是而不是引号(:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <regex>
using namespace std;
int main(int argc, char* argv[]) {
//string test = "<html><div><script>var link = "http://example.com/?key=dynamic_key";</script></div></html>";
string test = "<html><div><script>var link = "http://example.com/?key=dynamic_key";</script></div></html>";
//regex re("http://example.com/(*)");
regex re("http://example.com/([^"]*)"); // NOTE the escape "
smatch match;
if (regex_search(test, match, re)) {
cout<<"OK"<<endl;
cout << match.str(1) << 'n'; // first capture group
}
return 0;
}
输出:
OK
?key=dynamic_key
我认为这里有两个错误:
- 测试字符串的分隔不正确。尝试使用原始字符串文字
- regex也不太正确(我想您想匹配完整的链接(
此外,还有一个警告,regex和html并不总是能很好地协同工作。
示例代码列表
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <regex>
using namespace std;
int main(int argc, char* argv[]) {
string test = R"(<html><div><script>var link = "http://example.com/?key=dynamic_key";</script></div></html>)";
regex re( R"(http://example.com/[^"]*)" );
smatch match;
if (regex_search(test, match, re)) {
cout << "OK" << endl;
for (auto i : match) {
cout << i << endl;
}
}
return 0;
}
这里的输出是;
确定
http://example.com/?key=dynamic_key
请参阅此处获取实时样本。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 无法使函数公开。获取:"LNK2005"错误。如何调试链接器错误
- 错误 VSP1011:无法获取调试信息.与 /配置文件链接器开关链接
- 获取链接 创建flyweight_pattern时出错
- 使用自定义工具集获取动态退出析构函数链接错误 - eh 矢量析构函数
- 在可视化解决方案 c++ 中获取链接器错误
- 获取 constexpr 全局变量(不是静态成员)的链接器符号
- C++程序调用 C 函数 在 g++ 链接期间获取未定义的引用
- 如何在Visual Studio中的库编译时间中获取链接器错误
- 哪种方法更好获取静态链接DLL的模块句柄(HMODULE) - 使用GetModuleHandleEx()或LoadLibrary()?
- 在对类对象的赋值进行链接时获取垃圾值,使用按值返回类对象的赋值运算符重载
- 获取无效或损坏的文件LNK1107:尝试链接 OpenSceneGraph 教程.dll时无法0x378读取
- 在Visual C 项目中获取链接错误
- 在 VS 中,以编程方式获取链接器>其他库目录属性,或获取宏值
- 视觉获取链接错误:C++中的外部.如何访问在文件 A 中修改的变量的值.CPP在另一个文件 B .CPP中修改
- 如何在右键单击链接并从上下文菜单访问功能后获取链接的 DOM
- 获取链接器错误
- Qt中新的获取链接器和Makefile错误
- 重载模板类的运算符<<时获取链接器错误
- C++从html代码中获取链接