lupin218
lupin218

Reputation: 23

linux g++ regular expressions not working

I'm trying to find sub string using regular expressions on linux g++.

For example :

    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }

it works in windows c++ as well. but linux g++ not work. what's is the problem?

Upvotes: 0

Views: 558

Answers (2)

Kapil Kumar
Kapil Kumar

Reputation: 19

<regex> was implemented and released in GCC 4.9.0 so please check your gcc version and see below example:

#include <regex> //header  file for regex
#include <iostream>

int main(int argc, const char * argv[]){
    std::regex r("ab|bc|cd");
    std::cerr << "ab|bc|cd" << " matches ab? " << std::regex_match("sab", r) << std::endl;
    return 0;
}

Output:

ab|bc|cd matches ab? 1

Upvotes: 0

Alexander
Alexander

Reputation: 758

you do not need '\' before ':'. so the correct line is: std::regex re("SerialNumber: (.*)\n"); with this change your code works with gcc starting gcc 4.9.1. https://wandbox.org/permlink/uuVCxdtpHAjZTghP

Upvotes: 1

Related Questions