问题
如何使用C++缩小HTML?
资源
外部库可能是答案,但我更多地是在寻找对当前代码的改进。尽管我在倾听其他的可能性。
当前代码
这是我在“c++ of the following answer”中的解释。
我唯一需要改变的部分是:"(?ix)“。
...and几个逃生标志
#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, "");
}只有第一个正则表达式是从最初的帖子,另一个是我正在做的事情,应该被认为是远远没有完成。希望它能给我一个好的想法,让我知道我想要做些什么。
发布于 2013-06-12 05:53:34
Regexps是一个强大的工具,但我认为在这种情况下使用它们是个坏主意。例如,您提供的regexp是维护的噩梦。通过查看这个regexp,您不可能很快理解它应该匹配什么。
您需要一个html解析器来标记输入文件,或者允许您以流或对象树的形式访问令牌。基本上读取标记,丢弃那些标记和不需要的属性,然后将剩余的内容写入输出。使用这种方法可以让您开发解决方案的速度要比使用regexp解决方案的速度要快。
我认为您可能可以使用xml解析器,也可以使用html支持搜索xml解析器。
在C++中,libxml (它可能有HTML模块)、Qt4、tinyxml,加上libstrophe使用某种可以工作的xml解析器。
请注意,C++ (特别是C++03)可能不是这种程序的最佳语言。虽然我非常不喜欢python,但是python有“漂亮的汤”模块,可以很好地解决这类问题。
Qt4可能会工作,因为它提供了体面的unicode字符串类型(如果要解析html,您将需要它)。
https://stackoverflow.com/questions/16134469
复制相似问题