2012-11-28 90 views
1

我使用boost :: regex來解析某些格式化字符串,其中'%'符號是轉義字符。因爲我對boost :: regex沒有多少經驗,並且誠實地說正則表達式我會做一些試驗和錯誤。這段代碼是我想出來的一種原型。如何檢查匹配哪個匹配組(boost-regex)

std::string regex_string = 
      "(?:%d\\{(.*)\\})|"     //this group will catch string for formatting time 
      "(?:%([hHmMsSqQtTlLcCxXmMnNpP]))|" //symbols that have some meaning 
      "(?:\\{(.*?)\\})|"     //some other groups 
      "(?:%(.*?)\\s)|" 
      "(?:([^%]*))"; 

    boost::regex regex; 
    boost::smatch match; 

    try 
    { 
     regex.assign(regex_string, boost::regex_constants::icase); 
     boost::sregex_iterator res(pattern.begin(), pattern.end(), regex); 
     //pattern in line above is string which I'm parsing 
     boost::sregex_iterator end; 
     for(; res != end; ++res) 
     { 
      match = *res; 
      output << match.get_last_closed_paren(); 
      //I want to know if the thing that was just written to output is from group describing time string 
      output << "\n"; 
     } 


    } 
    catch(boost::regex_error &e) 
    { 
     output<<"regex error\n"; 
    } 

而且這個工作非常好,在輸出上我正是想要捕捉的東西。但我不知道它來自哪個組。我可以做一些類似match[index_of_time_group]!=""的東西,但這是一種脆弱的,看起來不太好。如果我更改regex_string指向組格式化時間的組捕獲字符串的索引也可能發生更改。

有沒有一個乾淨的方式來做到這一點?像命名組?我會很感激任何幫助。

回答

1

您可以使用boost::sub_match::matched布爾成員:

if(match[index_of_time_group].matched) process_it(match); 

也可以使用命名組在像正則表達式:(?<name_of_group>.*),以及與此上面的行可改爲:

if(match["name_of_group"].matched) process_it(match); 
+0

謝謝!經過一番調整,我想出了以下解決方案。 我改變了一部分正則表達式:'(?:%d \\ {(?

+0

所以你可以接受點擊綠色複選標記的答案。 – Rost

+0

5分鐘打我,正在編輯幾乎相同的代碼:-) – Rost

0

動態從成對的名稱/模式構建regex_string,並返回名稱 - >索引映射以及正則表達式。然後編寫一些代碼來確定匹配是否來自給定名稱。

如果你瘋了,你可以在編譯時(從標籤到索引的映射)。這不值得。