如何使用C++ 11计算匹配数std::regex?
std::regex re("[^\\s]+");
std::cout << re.matches("Harry Botter - The robot who lived.").count() << std::endl;
Run Code Online (Sandbox Code Playgroud)
预期产量:
7
Jam*_*lis 17
您可以使用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;
Run Code Online (Sandbox Code Playgroud)
你可以使用这个:
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);
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
std::cout << countMatchInRegex("Harry Botter - The robot who lived.", "[^\\s]+");
Run Code Online (Sandbox Code Playgroud)
输出:
7
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6540 次 |
| 最近记录: |