C++从html代码中获取链接

C++ get a link from html code

本文关键字:获取 链接 代码 html C++      更新时间:2023-10-16
#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

我认为这里有两个错误:

  1. 测试字符串的分隔不正确。尝试使用原始字符串文字
  2. 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

请参阅此处获取实时样本。