【问题标题】:regex works very slow正则表达式工作很慢
【发布时间】:2015-10-16 05:50:37
【问题描述】:

我有很多小于 64 kb 的文件,我需要使用下面的代码转换它们。

这是 QT 中的工作代码,QRegExp

我尝试在 MSVC 中用regex_replace 重写它,但遇到了工作非常缓慢的问题。

QT:

temp.replace(QRegExp("[ ]{0,}(=)[ ]{0,}"), QString("="));
temp.replace(QRegExp("[ ]{0,}(==)[ ]{0,}"), QString("=="));
temp.replace(QRegExp("[ ]{0,}(>)[ ]{0,}"), QString(">"));
temp.replace(QRegExp("[ ]{0,}(<)[ ]{0,}"), QString("<"));
temp.replace(QRegExp("[ ]{0,}(\\&\\&)[ ]{0,}"), QString("&&"));
temp.replace(QRegExp("[ ]{0,}(\\|\\|)[ ]{0,}"), QString("||"));
temp.replace(QRegExp("[ ]{0,}(\\})[ ]{0,}"), QString("}"));
temp.replace(QRegExp("[ ]{0,}(\\{)[ ]{0,}"), QString("{"));

MSVC:

temp = regex_replace(temp, std::regex("[ ]{0,}(=)[ ]{0,}"), "=");
temp = regex_replace(temp, std::regex("[ ]{0,}(==)[ ]{0,}"), "==");
temp = regex_replace(temp, std::regex("[ ]{0,}(>)[ ]{0,}"), ">");
temp = regex_replace(temp, std::regex("[ ]{0,}(<)[ ]{0,}"),"<" );
temp = regex_replace(temp, std::regex("[ ]{0,}(\\&\\&)[ ]{0,}"),"&&" );
temp = regex_replace(temp, std::regex("[ ]{0,}(\\|\\|)[ ]{0,}"),"||" );
temp = regex_replace(temp, std::regex("[ ]{0,}(\\})[ ]{0,}"), "}");
temp = regex_replace(temp, std::regex("[ ]{0,}(\\{)[ ]{0,}"),"{" );

例如:std::string temp(size of ~18kb) 每行处理大约 10 秒。

这里可能有什么问题?

【问题讨论】:

  • 改用Qt有哪些表现?我的意思是,其中一个比另一个好得多吗?从你写的内容看不清楚。
  • 您是否尝试过一个简单的正则表达式来检查时间是否被正则表达式自动机消耗或以某种不幸的方式读取文件?
  • @skypjack 我无法确定 QT 中的确切执行时间,但它是如此之快,以至于我不必考虑它。
  • @mcw 文件已经打开并且正则表达式与 std::string (for (auto it = stringList.begin(); it != stringList.end(); ++it) { auto temp = *it;) 一起使用
  • 如果您使用的是 Qt > 5.0,请尝试使用 QRegularExpression,看看它与 QRegExp 的比较:Qt 5 中引入的 QRegularExpression 类是对 QRegExp 的重大改进,就提供的 API 而言,支持的模式语法和执行速度。您为什么要放弃基于 Qt 的实现?

标签: c++ regex qt visual-studio-2015


【解决方案1】:

std::regex 可用的实现并不真正达到抢夺(还没有?),但boost::regex 相当快。

【讨论】:

  • 看起来 boost 库比 std 更快更优雅地解决了每个问题。
  • 好吧,boost::regex 是第一个。但我想知道为什么 clang/libc++ 的人没有将他们的 std::regex 建立在 boost::regex 上。它性能更好,并具有许可许可证。这意味着没有理由表现得更差。
猜你喜欢
  • 2013-07-11
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多