0

I want to extract track 2 data from a string, using std::regex in C++. I have a piece of code, but it does not work. This is the code:

std::string buff("this is ateststring;5581123456781323=160710212423468?hjks");
std::regex e (";\d{0,19}=\d{7}\w*\?", std::regex_constants::basic);
if(std::regex_match(buff, e))
                    {
                       cout << "Found!";
                    }
glennsl
  • 28,186
  • 12
  • 57
  • 75
  • 1
    What is "track 2 data"? Also, you need to escape your slashes. The string parser gets them before the regex engine does... – Cameron Dec 10 '13 at 17:05

1 Answers1

0

From the regex_match documentation:

The entire target sequence must match the regular expression for this function to return true (i.e., without any additional characters before or after the match). For a function that returns true when the match is only part of the sequence, see regex_search.

So try using regex_search instead:

std::regex e (";\\d{0,19}=\\d{7}\\w*\\?", std::regex_constants::basic);
if(std::regex_search(buff, e))
                {
                   cout << "Found!";
                }
Tim Pierce
  • 5,514
  • 1
  • 15
  • 31
  • Not working. `terminate called after throwing an instance of 'std::regex_error' what(): regex_error This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Process returned 3 (0x3) execution time : 0.016 s Press any key to continue.` – Brother Spr Dec 10 '13 at 17:14
  • `std::regex_constants::basic` does not seems to support `\d` or `\w`. Try `std::regex_constants::ECMAScript` (the default). – Guilherme Bernal Dec 10 '13 at 17:32
  • i used "std::regex_constants::ECMAScript", but i got the same error – Brother Spr Dec 10 '13 at 17:36
  • Here's some more useful information, if you're using G++: http://stackoverflow.com/questions/12530406/is-gcc4-7-buggy-about-regular-expressions. TL;DR: std::regex doesn't work in GCC prior to version 4.9. – Tim Pierce Dec 10 '13 at 17:42