c++ - 在 C++ 中使用 regex_iterator 的确切方法是什么?

标签 c++ regex

我一直在寻找一种计算字符串中特定类型的子字符串数量的好方法,比如说,我想计算字符串 'smstyuismsms' 中 'sms' 的出现次数。我在有人建议使用 regex_iterator 的论坛中找到了答案。但是,当我尝试如下时:

string in = "smstyuismssms";
cout << distance(regex_iterator(in.begin(), in.end(), regex("sms")),regex_iterator()) << "\n";

它抛出一个错误提示

error: missing template arguments before '(' token

那么,如果不是这样,那么使用正则表达式模板的正确方法是什么?请同时提供一些示例。

最佳答案

通过查看 documentation ,似乎 std::regex_iterator 是存在四个实例化的模板:

cregex_iterator    regex_iterator<const char*>
wcregex_iterator   regex_iterator<const wchar_t*>
sregex_iterator    regex_iterator<std::string::const_iterator>
wsregex_iterator   regex_iterator<std::wstring::const_iterator>

您应该改用这些。我的意思是,您始终可以自己传递模板参数,但这不必要地冗长。

来自 cppreference 示例:

auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex);

这很像 std::string/std::wstring,它们都是 std::basic_string 模板的实例化。基本上你的代码相当于使用 basic_string 并且不传递模板参数而不是直接使用 string/wstring。

关于c++ - 在 C++ 中使用 regex_iterator 的确切方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460242/

相关文章:

java - 选择没有子字符串的行

c++ - 减少 STL 类型调试 View 中的噪音

c++ - 使用 C++ 在 opencv 中检测图像中任何文本的位置

C++ 检查一个 int 或 char 并返回一个文本

c++ - 如何在 C++ 中修改 std::poisson_distribution 的平均值

c++ - OpenGL纹理倒置

python - 正则表达式匹配除 "/"之外的所有内容

regex - 如何测试两个字符串是否同时出现在另一个字符串中?

java - 更改 JS 正则表达式以在 Java 中工作

python - 多个短语匹配 Python Pandas