6

I simply want to match "{". But don't know why giving this error:

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted (core dumped)

Compilation on Ubuntu with g++ version 4.6.3

g++   -std=c++0x   a.c

Program

#include<iostream>
#include<regex>


using namespace std;

main(int argc,char**argv){

        if (regex_match("{1}" , std::regex ("[{]"))) {
                cout<<"Hello World"<<endl;
        }

}

I've also checked the ECMAScript details and this regular expression should match. It also does not match when I use like : std::regex ("\\{"))

What am I wrong?

user5858
  • 1,082
  • 4
  • 39
  • 79

2 Answers2

6

You need at least gcc 4.9 to make regexps work with gcc, once you will have 4.9 version add .* to make it match the rest of the string:

if (regex_match("{1}" , std::regex ("[{].*"))) {
                                        ^^

http://coliru.stacked-crooked.com/a/99e405e66906804d

Community
  • 1
  • 1
marcinj
  • 48,511
  • 9
  • 79
  • 100
1

I have the same error with you! And my IDE is Clion,
I choose the C++ version with Clion is C++17 and my test code is:

std::string pattern{ "http|hppts://\\w.*$" }; // url
std::regex re(pattern);
std::vector<std::string> str{ "http://blog.net/xxx", 
  "https://github.com/jasonhubs", "abcd://124.456",
   "abcdhttps://github.com/jasonhubs" 
 };
for (auto tmp : str) 
{
  bool ret = std::regex_search(tmp, re);
  if (ret) fprintf(stderr, "%s, can search\n", tmp.c_str());
  else fprintf(stderr, "%s, can not search\n", tmp.c_str());
}

and I solve it by updating the gcc and g++.

  1. sudo yum install centos-release-scl yum-utils
  2. sudo yum-config-manager --enable rhel-server-rhscl-7-rpms
  3. sudo yum install devtoolset-7
  4. scl enable devtoolset-7 bash
Jim U
  • 3,318
  • 1
  • 14
  • 24
Jason.Z
  • 9
  • 3