Regex:对非常数字符串使用smatch
Regex: Using smatch on a non-const 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>;
因此,当使用非常量迭代器begin()
和end()
调用regex_search
时,它无法推导出正确的重载。
你可以通过几种方式绕过这一点:
使用
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";
使用非常量std::string
,您可以简单地使用:
std::regex_search (str.cbegin(), str.cend(), match, rgx) )
~~ ~~