1

我想在 Linux 中解析 cpu 信息。我写了这样的代码:

// 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;

但它返回空字符串。怎么了?

4

3 回答 3

5

并非所有编译器都支持完整的 C++11 规范。值得注意的是,regex_search在 GCC 中不起作用(从 4.7.1 版开始),但在 VC++ 2010 中起作用。

于 2012-08-08T10:02:53.920 回答
3

您没有在表达式中指定任何捕获。

鉴于 的结构/proc/cpuinfo,我可能更喜欢面向行的输入,使用std::getline,而不是尝试一次完成所有事情。所以你最终会得到类似的东西:

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;
    }
}

我不清楚你想要什么作为输出。可能您还必须捕获该processor行,并在处理器信息行的开头输出该行。

需要注意的重要事项是:

  1. 您需要接受不同数量的空白:"\\s*"用于 0 或更多,"\\s+"用于一个或多个空白字符。

  2. 您需要使用括号来分隔要捕获的内容。

(FWIW:我的陈述实际上是基于boost::regex,因为我无法访问std::regex。但是,我认为它们非常相似,并且我的上述陈述适用于两者。)

于 2012-08-08T10:44:54.960 回答
2

试试std::regex reg("model_name *: *")。在我的 cpuinfo 中,冒号前有空格。

于 2012-08-08T10:06:23.667 回答