使用 C++ std::sregex_token_iterator 提取 HTML 注释
Extract HTML comments using C++ std::sregex_token_iterator
我正在尝试从HTML源代码中提取注释部分。它有点工作,但不完全是。
<html><body>Login Successful!</body><!-- EXTRACT-THIS --></html>
这是我到目前为止的代码:
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <regex>
using namespace std;
int main()
{
string s =
"<html><body>Login Successful!</body><!-- EXTRACT-THIS --></html>";
// Regular expression to extract from HTML comment
// <!-- comment -->
regex r("[<!--rnt][rnt-->]");
for (sregex_token_iterator it = sregex_token_iterator(
s.begin(),
s.end(),
r,
-1);
it != sregex_token_iterator(); ++it)
{
cout << "TOKEN: " << (string) *it << endl;
}
return 0;
}
我想我的主要问题是有没有办法改进我的正则表达式?
让我们从一个包含多个注释部分的std::string
开始:
string s = "<html><body>Login Successful!</body><!-- EXTRACT-THIS --><p>Test</p><!-- XXX --></html>";
删除注释并打印 HTML 标记
如果要从此字符串中删除HTML注释,可以这样做:
regex r("(<\!--[^>]*-->)");
// split the string using the regular expression
sregex_token_iterator iterator = sregex_token_iterator(s.begin(), s.end(), r, -1);
sregex_token_iterator end;
for (; iterator != end; ++iterator)
{
cout << "TOKEN: " << (string) *iterator << endl;
}
此代码打印:
TOKEN: <html><body>Login Successful!</body>
TOKEN: <p>Test</p>
TOKEN: </html>
删除 HTML 标记并打印注释
如果要从字符串中提取注释,可以使用如下所示的std::sregex_iterator
:
regex r("(<\!--[^>]*-->)");
std::sregex_iterator next(s.begin(), s.end(), r);
std::sregex_iterator end;
while (next != end) {
std::smatch match = *next;
std::cout << match.str() << "n";
next++;
}
此代码打印:
<!-- EXTRACT-THIS -->
<!-- XXX -->
手动解析注释标记
另一种选择是手动查找和循环访问开始和结束标记。我们可以使用std::string::find()
和std::string::substr()
方法:
const std::string OPEN_TAG = "<!--";
const std::string CLOSE_TAG = "-->";
auto posOpen = s.find(OPEN_TAG, 0);
while (posOpen != std::string::npos) {
auto posClose = s.find(CLOSE_TAG, posOpen);
std::cout << s.substr(posOpen, posClose - posOpen + CLOSE_TAG.length()) << 'n';
posOpen = s.find(OPEN_TAG, posClose + CLOSE_TAG.length());
}
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么istream不支持右值提取
- 如何设置一个范围来提取我想要获得的信息
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 从 std::vector<无符号字符>切片中提取 int?
- 使用 C++ std::sregex_token_iterator 提取 HTML 注释
- C :如何将多个URL从网站HTML提取到向量
- 如何使用FSCANF提取HTML
- 使用 c++/boost::regex 提取 HTML 文件的特定部分
- 是否有用于从HTML页面中提取数据的库
- 使用Boost.从HTML中提取某些标签/属性
- 在c++/ c++中提取HTML文件的外链
- linux下从HTML到c++的关键字提取
- 用C++提取HTML标记
- 用c/c++编程从html文件中提取表