gpt4 book ai didi

c++ - 在 C++ 中使用 Boost 正则表达式缩小 HTML

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:18:27 25 4
gpt4 key购买 nike

问题

如何使用 C++ 压缩 HTML?

资源

外部库可能是答案,但我更希望改进我当前的代码。尽管我很期待其他可能性。

当前代码

这是我对 the following answer 的 C++ 解释.

我必须从原始帖子更改的唯一部分是顶部的这部分:“(?ix)”
...和一些逃生标志

#include <boost/regex.hpp>
void minifyhtml(string* s) {
boost::regex nowhitespace(
"(?ix)"
"(?>" // Match all whitespans other than single space.
"[^\\S ]\\s*" // Either one [\t\r\n\f\v] and zero or more ws,
"| \\s{2,}" // or two or more consecutive-any-whitespace.
")" // Note: The remaining regex consumes no text at all...
"(?=" // Ensure we are not in a blacklist tag.
"[^<]*+" // Either zero or more non-"<" {normal*}
"(?:" // Begin {(special normal*)*} construct
"<" // or a < starting a non-blacklist tag.
"(?!/?(?:textarea|pre|script)\\b)"
"[^<]*+" // more non-"<" {normal*}
")*+" // Finish "unrolling-the-loop"
"(?:" // Begin alternation group.
"<" // Either a blacklist start tag.
"(?>textarea|pre|script)\\b"
"| \\z" // or end of file.
")" // End alternation group.
")" // If we made it here, we are not in a blacklist tag.
);

// @todo Don't remove conditional html comments
boost::regex nocomments("<!--(.*)-->");

*s = boost::regex_replace(*s, nowhitespace, " ");
*s = boost::regex_replace(*s, nocomments, "");
}

只有第一个正则表达式来自原始帖子,另一个正则表达式是我正在处理的,应该被认为远未完成。不过,它应该能很好地说明我要完成的工作。

最佳答案

正则表达式是一个强大的工具,但我认为在这种情况下使用它们不是一个好主意。例如,您提供的正则表达式是维护噩梦。通过查看此正则表达式,您无法快速理解它到底应该匹配什么。

您需要一个 html 解析器来标记输入文件,或者允许您以流或对象树的形式访问标记。基本上读取标记,丢弃不需要的标记和属性,然后将剩余的写入输出。与尝试使用正则表达式解决问题相比,使用类似这样的方法可以让您更快地开发解决方案。

认为您可以使用 xml 解析器,或者您可以搜索支持 html 的 xml 解析器。

在 C++ 中,libxml(可能具有 HTML 支持模块)、Qt 4、tinyxml 以及 libstrophe 使用某种可以工作的 xml 解析器。

请注意,C++(尤其是 C++03)可能不是此类程序的最佳语言。虽然我非常不喜欢 python,但 python 有“Beautiful Soup”模块,可以很好地解决这类问题。

Qt 4 可能会工作,因为它提供了合适的 unicode 字符串类型(如果您要解析 html,您将需要它)。

关于c++ - 在 C++ 中使用 Boost 正则表达式缩小 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com