linux 下使用clion 的朋友 可能会碰到这样的问题,某些C++正则表达式会抛出异常,例如C++primer上的一个例子
#include <iostream>
#include <regex>
using namespace std;
int main(void) {
//查找不在字符 c 之后的字符串
string pattern("[^c]ei");
//我们需要包含pattern的整个单词
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
regex r(pattern); //构造一个用于查找模式的regex
smatch results; //定义一个对象保存搜索结果
//定义一个string 保存与模式匹配和不匹配的文本
string test_str = "receipt freind theif receive";
//用r 在test——str中查找与pattern匹配的子串
if (regex_search(test_str, results, r)) //如果有匹配的子串
cout << results.str() << endl;
}
抛出如下异常
<span style="color:#ff0000;"><strong>terminate called after throwing an instance of 'std::regex_error'
what(): regex_error</strong></span>
编译成功后运行时出现异常,而代码并没有错误。原因可能是 编译器的问题,在一个在线平台 www.ideone.com 上是可以正常编译运行的。
我们把clion 编译器替换成 g++-4.9或者clang++3.8就可以了
clang++-3.8的下载方法大家可自行google ,这里不再赘述,
g++-4.9的安装方法如下
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install g++-4.9
gcc-4.9 -v
上面是ubuntu的命令,其他自行替换
这里说一下clion如何替换clang++-3.8,g++类推 ——摘自 clion FAQ https://intellij-support.jetbrains.com/hc/en-us/articles/207251865-How-can-I-change-compilers-in-CLion-
Since CLion relies on CMake build system. To change the compiler used in CLion, use method #2 from the official CMake documentation.
Go to Preferences/Settings | Build, Execution, Deployment | CMake | CMake options and pass the following commands:
-D CMAKE_C_COMPILER=<your_path_to_c_compiler> -D CMAKE_CXX_COMPILER=<your_path_to_cxx_compiler>