-1

Below is the C++ program which uses regex to match a string, but is not working. My OS is Ubuntu Linux and compiler is standard C++ compiler which comes with ubuntu.

#include <iostream>
#include <regex>

using namespace std;

int main() {
    const char s[] = "This is a target string";
    regex e ("^([0-9a-zA-Z]*).*?");
    cmatch matches;
    if(regex_match(s, matches, e)) {
        cout << "Match found" << endl;
        for (int i = 0; i < matches.size(); ++i) {
            cout << matches[i] << endl;
        }
    }
    return 0;
}

On compiling using g++ like below

g++ -o test test.cpp -std=c++11

And running the program is failing with the below output

terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
[1]    24898 abort (core dumped)  ./test

The pattern is working fine and I tried it in rubular.com.I am expecting it to print

Match Found
This is a target string
This

I am new to using regular expressions in C++. Please point me in the right direction.

lucifer
  • 110
  • 8
  • 1
    Is your compiler version GCC 4.8? (Default in Ubuntu 14.04 I believe.) – n.caillou May 04 '17 at 03:42
  • I can't reproduce, but did you intend to include the question mark at the end of the string? Normally, `?` is a special character, but here it doesn't apply to anything, since `.*` is already matching 0 or more. So I think it will be interpreted as matching a literal `?`, but, it may not be well defined – happydave May 04 '17 at 03:47
  • 1
    Try: `g++ --version` and if the version is less than `GCC 4.9` then regex doesn't work. You need to upgrade the compiler. – Galik May 04 '17 at 04:01
  • Compiler info g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4 Copyright (C) 2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. – lucifer May 04 '17 at 04:03
  • @happydave -- the `?` at the end of the repetition makes it non-greedy, i.e., it will select the **shortest** subexpression that results in a complete match; ordinarily repetitions are greedy, and select the **longest** subexpression. – Pete Becker May 04 '17 at 12:07
  • @PeteBecker: Ah, thanks. I learned something new. – happydave May 10 '17 at 14:37

1 Answers1

0

Can you use try/catch and catch the regex_error and print e.what() to know what excatly went wrong.

Btw, it worked perfectly with my gcc with c++11 flag

catch (const std::regex_error& e) {
        std::cout << "regex_error caught: " << e.what() << '\n';
        if (e.code() == std::regex_constants::error_brack) {
            std::cout << "The code was error_brack\n";
        }
    }
praveen
  • 71
  • 6