我正在尝试运行CPPReference's regex_search example:
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string lines[] = {"Roses are #ff0000",
"violets are #0000ff",
"all of my base are belong to you"};
std::regex color_regex("#([a-f0-9]{2})"
"([a-f0-9]{2})"
"([a-f0-9]{2})");
for (const auto &line : lines) {
std::cout << line << ": "
<< std::regex_search(line, color_regex) << '\n';
}
std::smatch color_match;
for (const auto &line : lines) {
std::regex_search(line, color_match, color_regex);
std::cout << "matches for '" << line << "'\n";
for (size_t i = 0; i < color_match.size(); ++i)
std::cout << i << ": " << color_match[i] << '\n';
}
}
该程序使用Clang ++ 3.4-1ubuntu3和GCC 4.8.2编译,但立即运行会出现此错误:
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error
Aborted (core dumped)
This question表示问题与GCC有关,但与Clang编译会产生同样的问题。甚至使用以下命令在每一步显式传入库:
clang++ -stdlib=libstdc++ -std=c++11 -H -c regex.cpp -o object.o && clang++ -stdlib=libstdc++ object.o -o regex
在运行时导致错误,尽管第一个命令的输出的最后几行是:
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_constants.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_error.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_cursor.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_nfa.h
... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_nfa.tcc
.... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/regex
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_compiler.h
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_grep_matcher.h
... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex_grep_matcher.tcc
.... /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/regex
.. /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/regex.h
...表示我的系统上存在相应的标题。
答案 0 :(得分:5)
您仍然使用不完整的gcc
标准库实现,甚至明确告诉clang
将其与-stdlib=libstdc++
一起使用。
clang
附带的标准库实现为libc++
,因此您需要-stdlib=libc++
。