c++ - 正则表达式:在非常量字符串上使用 smatch

标签 c++ regex string

我有以下 MWE,它在常量字符串中查找两个单词:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    const std::string str = " \"car\":\"1\", \"boats\":2, \"three\":3, \"two\":22 ";

    const std::regex rgx("\"car\"|\"boat\"");
    std::smatch match;

    std::cout << (std::regex_search(str.begin(), str.end(), match, rgx)) << "\n";

    return 0;
}

这按预期工作,但是,就我而言,我处理的不是常量字符串,而是变量字符串。看起来上面的方法只适用于常量字符串。是否可以制作一个不需要 const str 的版本?

最佳答案

问题是 smatch 暗示 regex_search 使用的双向迭代器类型是 std::string::const_iterator :

基本上它是一个如下所示的别名:

using std::smatch = std::match_results<std::string::const_iterator>;

所以当你调用regex_search时使用非常量迭代器 begin()end()它无法推断出适当的过载。

您可以通过几种方式解决这个问题:

  • 使用cbegin()cend()P0W建议:

  • 使用str本身:regex_search(str, match, rgx)

  • 避免smatch :

(手动使用match_results)

std::match_results<std::string::iterator> match;
std::cout << (std::regex_search(str.begin(), str.end(), match, rgx)) << "\n";

关于c++ - 正则表达式:在非常量字符串上使用 smatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138678/

相关文章:

python - 以编程方式将 Python 输入括在引号中

c++ - 如何清除String流中的内容?

c++ - 检查浮点参数是否正确

c++ - 删除多个字符指针

c++ - 以 std::function 作为参数的构造函数模板参数推导

javascript - 如何使用 vuelidate 检查两个正则表达式值

python - 正则表达式查找两个字符串的最长公共(public)前缀

javascript - 我可以使用未知字符串替换吗

python - 四位数字符串编号到两位数字符串

c++ - 如何从Syslog-NG/Syslog获取数据