我有一个字符串 - 需要使用正则表达式解析的 html 代码。我需要将页面上的所有 URL 写入 std::vector href=""。我的常规 C++ 代码不起作用。
#include <regex>
#include <iostream>
#include <string>
using std::string;
using std::regex;
using std::cout;
using std::endl;
using std::sregex_iterator;
using std::smatch;
int main()
{
string subject("<head><title>Search engines</title></head><body><a href=\"https://yandex.ru\">Yandex</a><a href=\"https://google.com\"></a></body>");
try {
regex re("<\\s*A\\s+[^>]*href\\s*=\\s*\"([^\"]*)\"");
sregex_iterator next(subject.begin(), subject.end(), re);
sregex_iterator end;
if (next == end)
cout << "Oops" << endl;
while (next != end) {
smatch match = *next;
cout << match.str() << endl;
next++;
}
} catch (std::regex_error& e) {
; // Syntax error in the regular expression
}
return 0;
}
只有 Python'ovsky 有效。
#!/usr/bin/python3
import re
html = '<head><title>Search engines</title></head><body><a href="https://yandex.ru">Yandex</a><a href="https:/google.com"></a></body>'
title = re.findall(r'<title>(.*?)</title>', html)[0]
links = [ x[1] for x in re.findall(r'<a\s+(?:[^>]*?\s+)?href=(["\'])(.*?)\1', html)]
print (title)
print (links)
我想你可以花一周时间翻阅 Jeffrey Friedl 的正则表达式指南和 regex 库并得到你想要的结果,但 stackoverflow 并不是为了“阅读 Friedl,不要要求消化粥”之类的建议。此外,对于这样一个看似有用的问题,堆栈上没有答案可以让它发挥作用。
您可以使用 flag 修复代码
std::regex_constants::icase,也可以使用sregex_token_iteratorc1作为第四个参数(以获取捕获子模式 #1 中的值)。在 Pythonre.findall中,如果在模式中指定了捕获子模式,则仅返回捕获的子字符串,而 C++ 中没有这种方法。一个有效的 C++ 代码示例: