我使用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
指向組格式化時間的組捕獲字符串的索引也可能發生更改。
有沒有一個乾淨的方式來做到這一點?像命名組?我會很感激任何幫助。
謝謝!經過一番調整,我想出了以下解決方案。 我改變了一部分正則表達式:'(?:%d \\ {(?
所以你可以接受點擊綠色複選標記的答案。 – Rost
5分鐘打我,正在編輯幾乎相同的代碼:-) – Rost