C STD Regexp为什么不匹配

c++ std regexp why not matched?

本文关键字:不匹配 为什么 Regexp STD      更新时间:2023-10-16

i wannna获取关键字匹配长度

但是,始终匹配计数为零

为什么..?

string text = "sp_call('%1','%2','%a');";
std::regex regexp("%[0-9]");
std::smatch m;
std::regex_match(text, m, regexp);
int length = m.size();
cout << text.c_str() << " matched " << length << endl; // always 0

regex_match

确定正则表达式E是否匹配整个目标字符序列,该序列可以指定为std :: string,c-string或Iterator对。

您需要使用regex_search

确定正则表达E与目标字符序列中的某些子序列之间是否有匹配。

您也可以使用regex_iterator,此处的示例:

string text = "sp_call('%1','%2','%a');";
std::regex regexp("%[0-9]");
auto words_begin =
    std::sregex_iterator(text.begin(), text.end(), regexp);
auto words_end = std::sregex_iterator();
std::cout << "Found "
    << std::distance(words_begin, words_end)
    << " words:n";
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
    std::smatch match = *i;
    std::string match_str = match.str();
    std::cout << match_str << 'n';
}

找到了2个单词:
%1
%2