c++ - 减少 C++ 中的 std::regex 编译时间

标签 c++ regex c++11

我正在使用 std::regex r("-?[0-9]*(.[0-9]+)?(e-?[0-9]+)?") 来验证数字(整数/定点数/ float )。 MWE如下:

#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <algorithm>

using namespace std;

bool isNumber(string s) {
  // can ignore all whitespace
  s.erase(remove(s.begin(), s.end(), ' '), s.end());
  std::regex r("-?[0-9]*(.[0-9]+)?(e-?[0-9]+)?");
  return regex_match(s, r);
}

int main() {
  std::vector<string> test{
    "3", "-3", // ints
      "1 3", " 13", " 1 3 ", // weird spacing
      "0.1", "-100.123123", "1000.12312", // fixed point
      "1e5", "1e-5", "1.5e-10", "1a.512e4", // floating point
      "a", "1a", "baaa", "1a", // invalid
      "1e--5", "1e-", //invalid
      };

  for (auto t : test) {
    cout.width(20); cout << t << " " << isNumber(t) << endl;
  }

  return 0;
}

我注意到编译时间比我预期的要长:

  • gcc 5.4 -O0 -std=c++11,2.3 秒
  • gcc 5.4 -O2 -std=c++11,3.4 秒
  • clang++ 3.8 -O0 -std=c++11,1.8 秒
  • clang++ 3.8 -O2 -std=c++11,3.7 秒

我用这个做在线评委投稿,在编译阶段有时间限制。

所以,显而易见的问题:

  • 为什么编译时间这么长?我的印象是,当我在 vim/emacs/grep/ack/ag 等(在同一台机器上)中使用正则表达式时,编译真的比这少得多。
  • 有什么方法可以减少 C++ 中正则表达式的编译时间吗?

最佳答案

您当然可以通过适本地转义小数点来减轻正则表达式的计算负担:-?[0-9]*(\.[0-9]+)?(e-?[0-9 ]+)? 这当然会防止您对数字返回误报,例如:“1 3”(别担心,这是 2 个数字是件好事。)但是在这种情况下和许多其他情况下你弯腰使用正则表达式 "Now you have 2 problems" .

使用 istringstream将为这个问题提供更专业、更可靠的解决方案:

bool isNumber(const string& s) {
    long double t;
    istringstream r(s);

    return r >> t >> ws && r.eof();
}

Live Example

关于c++ - 减少 C++ 中的 std::regex 编译时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41861222/

相关文章:

正则表达式 - 选择不完全或部分匹配的词

java - 正则表达式匹配两个随机字符串之间的可选字符串

regex - Stack Overflow 如何生成其对 SEO 友好的 URL?

c++ - 对于具有引用返回类型的搜索算法,默认返回值应该是什么?

c++ - 如何将 constexpr 作为模板参数传递?

c++ - 二维指针数组

c++ - 绕过基类构造函数调用

c++ - 什么是 'thunk' ?

c++ - 如何用 natvis 可视化一个简单的 std::string?

c++11 - 如何在 Qt Creator 2.8.0 的通用项目中启用 C++11 支持?