【问题标题】:What is the exact way of using regex_iterator in C++?在 C++ 中使用 regex_iterator 的确切方法是什么?
【发布时间】:2015-05-26 13:39:11
【问题描述】:

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

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

它会抛出一个错误提示

错误:在 '(' 标记之前缺少模板参数

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

【问题讨论】:

    标签: c++ regex


    【解决方案1】:

    通过查看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 而不是传递模板参数。

    【讨论】:

    • 嗨!我首先仅使用相同的示例进行了尝试。但是 sregex_iterator 抛出了一个错误“未定义的正则表达式引用”。当我搜索这个问题时,我发现我正在使用的编译器(gcc4.8.1)可能不支持这个实例化。所以,然后,我切换到 regex_iterator。
    • @timidgeek See this question,恐怕你的编译器可能太旧了。
    • 很好。我将更新我的编译器并询问是否仍然存在任何问题。谢谢。
    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多