2012-08-08 49 views
1

我想解析Linux中的cpu信息。我寫了這樣的代碼:C++中的正則表達式11

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

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

+0

難道你不是指'cmatch'?你可以發佈整個代碼和'cpuinfo'的內容嗎? – slaphappy 2012-08-08 10:01:49

+0

看到此主題「regex_match和regex_search之間的區別?」 (http://stackoverflow.com/questions/11628047/difference-between-regex-match-and-regex-search) – SChepurin 2012-08-08 10:44:02

+0

想要補充的是,它在VC++ 2010中的工作原理,由James Kanze在下面的答案中糾正了表達式。 – SChepurin 2012-08-08 10:59:19

回答

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訪問我認爲他們很相似,但是 ,而我上面的說明適用。兩者)。

+0

很好的答案,謝謝;)。順便說一句,替換,請'線路''line.c_str()'在'regex_match'中。 – Ockonal 2012-08-08 11:21:16

+0

@Ockonal爲什麼要改變?兩者都在標準中定義(並且都使用'boost :: regex')。 – 2012-08-08 11:55:09

+0

在我的4.7.1 gcc中有一個與此相關的錯誤 – Ockonal 2012-08-08 12:03:36

5

並非所有的編譯器都支持完整的C++ 11規範。值得注意的是,regex_search在GCC中不起作用(從版本4.7.1開始),但它在VC++ 2010中。

+1

另請參閱:http://gcc.gnu.org/onlinedocs/gcc-4.7.1/libstdc++/manual/manual/status.html#status.iso.2011 – moooeeeep 2012-08-08 10:35:10

2

嘗試std::regex reg("model_name *: *")。在我的cpuinfo中有冒號前的空格。

+0

沒有捕獲,他仍然不會獲取他所需要的信息需要。 – 2012-08-08 10:46:31