使用 C++ std::sregex_token_iterator 提取 HTML 注释

Extract HTML comments using C++ std::sregex_token_iterator

本文关键字:提取 HTML 注释 iterator token C++ sregex 使用 std      更新时间:2023-10-16

我正在尝试从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());
}