如何計算使用C++ 11的匹配數?計數匹配數
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
預期輸出:
7
如何計算使用C++ 11的匹配數?計數匹配數
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
預期輸出:
7
您可以使用regex_iterator
生成所有的比賽,然後使用distance
算來:
std::regex const expression("[^\\s]+");
std::string const text("Harry Botter - The robot who lived.");
std::ptrdiff_t const match_count(std::distance(
std::sregex_iterator(text.begin(), text.end(), expression),
std::sregex_iterator()));
std::cout << match_count << std::endl;
你能解釋一下'std :: sregex_iterator'返回什麼和兩者之間的距離? –
@muntoo:'sregex_iterator'是'regex_iterator'上的typedef,它遍歷文本中的所有匹配項。 'distance'是標準庫函數,用於計算迭代器範圍內的元素數量(因此,在這種情況下,它會讀取所有匹配項並返回其中的數量)。 –
嗨。即使這是一箇舊線程:我認爲你可以放棄match_count操作(在C++ 11中不存在),因爲(w)sregex :: iterator已經迭代了,就像你在比賽中提到你自己一樣。因此,std :: distance應返回匹配計數。我嘗試使用gcc 4.6.1和VS 2013沒有match_count,它工作得很好。 – gilgamash
您可以使用此:
int countMatchInRegex(std::string s, std::string re)
{
std::regex words_regex(re);
auto words_begin = std::sregex_iterator(
s.begin(), s.end(), words_regex);
auto words_end = std::sregex_iterator();
return std::distance(words_begin, words_end);
}
實例:
std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\\s]+");
輸出:
7
和你的輸出是.... –
@EdHeal我得到[編譯錯誤](http://ideone.com/uxyrV): '錯誤:'regex_count'未在此範圍內聲明。 ;) –