2016-08-21 154 views
1

在我的代碼中,我想處理基於包含<>的括號。爲此,我想通過字符串並逐個替換括號,並根據括號內的內容做一些事情。C++無法讓regex_match工作

string msg = "This is an <red>Example<> message. For <blue>exampleness' sake<>."; 
std::regex rexpr("<[a-zA-Z]*>"); 

// replace the first set of <> with %c, return the non-replaced version, and process it. 
while(true){ 
    std::smatch smatch; 
    // cant find any matches... 
    std::regex_match(msg, smatch, rexpr); 
    string key = smatch[0]; // this is empty from the start. 

    if(key.empty()) break; // no more keys, break. 

    // replace <...> 
    std::regex_replace(msg, rexpr, "%c", std::regex_constants::format_first_only); 

    if(key.size() == 2) continue; // closing brackets, nothing to process 

    // cut the brackets 
    key = key.substr(1, key.size() - 1); 

    // process the key. 
    // ... 
} 
+0

會發生什麼,如果你執行該代碼? – dwo

+0

沒有任何東西被替換。和regex_match無法找到任何匹配。 – val

+0

對於基本上是'msg.find('<')'和'msg.find('>')'的東西,這是很多機制。 –

回答

1

你需要把括號()各地要抓住事物:

string msg = "This is an <red>Example<> message. For <blue>exampleness' sake<>."; 
std::regex rexpr("(<[a-zA-Z]*>)"); 

smatch match; 
if(regex_search(msg, match, rexpr)) { 
     cout << match[0] << endl; 
} 

輸出:

<red> 
+0

是的,它現在可以工作了,還必須將r​​egexp_replace的結果賦值給msg,才能真正更改消息字符串,並且不會發生無限循環。 – val

+0

很高興聽到這解決了你的問題:) –