正则表达式:在非const字符串上使用smatch

时间:2017-11-06 14:01:22

标签: 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的版本?

2 个答案:

答案 0 :(得分:3)

问题是smatch意味着用于regex_search的双向迭代器类型是std::string::const_iterator

基本上它是一个看起来像这样的别名:

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

因此,当您使用非const迭代器regex_searchbegin()调用end()时,它无法推断出正确的过载。

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

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

  • 单独使用strregex_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";

答案 1 :(得分:2)

使用非const # multiply each item in d by corresponding number in y xy <- map2(d, y, ~ map2(.x, .y, `*`)) # sum the first item in each list, then second item in each list denominator <- map(transpose(xy), reduce, `+`) # divide each item by the denominator tau <- map(xy, ~ map2(., denominator, `/`)) # take the mean of each vector within each list w <- map(tau, ~ map(., mean)) ,您可以简单地使用:

std::string