我正在使用 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();
}
关于c++ - 减少 C++ 中的 std::regex 编译时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41861222/