Max Frai
Max Frai

Reputation: 64266

Regular expressions in c++11

I want to parser cpu info in Linux. I wrote such code:

// Returns full data of the file in a string
std::string filedata = readFile("/proc/cpuinfo");

std::cmath results;
// In file that string looks like: 'model name : Intel ...'
std::regex reg("model name: *");
std::regex_search(filedata.c_str(), results, reg);

std::cout << results[0] << " " << results[1] << std::endl;

But it returns empty string. What's wrong?

Upvotes: 1

Views: 1205

Answers (3)

James Kanze
James Kanze

Reputation: 153899

You didn't specify any capture in your expression.

Given the structure of /proc/cpuinfo, I'd probably prefer a line oriented input, using std::getline, rather than trying to do everything at once. So you'ld end up with something like:

std::string line;
while ( std::getline( input, line ) ) {
    static std::regex const procInfo( "model name\\s*: (.*)" );
    std::cmatch results;
    if ( std::regex_match( line, results, procInfo ) ) {
        std::cout << "???" << " " << results[1] << std::endl;
    }
}

It's not clear to me what you wanted as output. Probably, you also have to capture the processor line as well, and output that at the start of the processor info line.

The important things to note are:

  1. You need to accept varying amounts of white space: use "\\s*" for 0 or more, "\\s+" for one or more whitespace characters.

  2. You need to use parentheses to delimit what you want to capture.

(FWIW: I'm actually basing my statements on boost::regex, since I don't have access to std::regex. I think that they're pretty similar, however, and that my statements above apply to both.)

Upvotes: 3

Some programmer dude
Some programmer dude

Reputation: 409136

Not all compilers support the full C++11 specification yet. Notably, regex_search does not work in GCC (as of version 4.7.1), but it does in VC++ 2010.

Upvotes: 5

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12403

Try std::regex reg("model_name *: *"). In my cpuinfo there are spaces before colon.

Upvotes: 2

Related Questions