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?
You didn’t specify any capture in your expression.
Given the structure of
/proc/cpuinfo, I’d probably prefer a lineoriented input, using
std::getline, rather than trying to doeverything at once. So you’ld end up with something like:
It’s not clear to me what you wanted as output. Probably, you also
have to capture the
processorline as well, and output that at thestart of the processor info line.
The important things to note are:
You need to accept varying amounts of white space: use
"\\s*"for 0 or more,"\\s+"for one or more whitespace characters.You need to use parentheses to delimit what you want to capture.
(FWIW: I’m actually basing my statements on
boost::regex, since Idon’t have access to
std::regex. I think that they’re pretty similar,however, and that my statements above apply to both.)