terminate called after throwing an instance of ‘std::regex_error‘

项目场景:

#include <iostream>
#include <regex>
using namespace std;

int main()
{
    regex r1("S");
    printf("S works.\n");
    regex r2(".");
    printf(". works.\n");
    regex r3(".+");
    printf(".+ works.\n");
    regex r4("[0-9]");
    printf("[0-9] works.\n");
    return 0;
}

问题描述:

S works.
. works.
.+ works.
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted

解决分析:

该错误是因为默认情况下创建正则表达式对表达式使用ECMAScript语法,该表达式不支持括号。应该使用basicor 标志来声明表达式:

std::regex r4("[0-9]", std::regex_constants::basic);