Regex:对非常数字符串使用smatch

Regex: Using smatch on a non-const string

本文关键字:smatch 字符串 数字 非常 Regex      更新时间:2023-10-16

我有以下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>;

因此,当使用非常量迭代器begin()end()调用regex_search时,它无法推导出正确的重载。

你可以通过几种方式绕过这一点:

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

使用非常量std::string,您可以简单地使用:

std::regex_search (str.cbegin(), str.cend(), match, rgx) )
~~            ~~