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