gpt4 book ai didi

c++ - std::match_results::size 返回什么?

转载 作者:可可西里 更新时间:2023-11-01 17:36:49 26 4
gpt4 key购买 nike

我对以下 C++11 代码有点困惑:

#include <iostream>
#include <string>
#include <regex>

int main()
{
std::string haystack("abcdefabcghiabc");
std::regex needle("abc");
std::smatch matches;
std::regex_search(haystack, matches, needle);
std::cout << matches.size() << std::endl;
}

我希望它打印出 3 但我却得到了 1。我错过了什么吗?

最佳答案

你得到 1 因为 regex_search仅返回 1 个匹配项,size() 将返回捕获组的数量 + 整个匹配值。

你的匹配是...:

Object of a match_results type (such as cmatch or smatch) that is filled by this function with information about the match results and any submatches found.

If [the regex search is] successful, it is not empty and contains a series of sub_match objects: the first sub_match element corresponds to the entire match, and, if the regex expression contained sub-expressions to be matched (i.e., parentheses-delimited groups), their corresponding sub-matches are stored as successive sub_match elements in the match_results object.

这是一个可以找到多个匹配项的代码:

#include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
string str("abcdefabcghiabc");
int i = 0;
regex rgx1("abc");
smatch smtch;
while (regex_search(str, smtch, rgx1)) {
std::cout << i << ": " << smtch[0] << std::endl;
i += 1;
str = smtch.suffix().str();
}
return 0;
}

参见 IDEONE demo返回 abc 3 次。

由于此方法会破坏输入字符串,这里是另一种基于 std::sregex_iterator 的替代方法(std::wsregex_iterator 应在您的主题是 std::wstring 对象):

int main() {
std::regex r("ab(c)");
std::string s = "abcdefabcghiabc";
for(std::sregex_iterator i = std::sregex_iterator(s.begin(), s.end(), r);
i != std::sregex_iterator();
++i)
{
std::smatch m = *i;
std::cout << "Match value: " << m.str() << " at Position " << m.position() << '\n';
std::cout << " Capture: " << m[1].str() << " at Position " << m.position(1) << '\n';
}
return 0;
}

参见 IDEONE demo , 回归

Match value: abc at Position 0
Capture: c at Position 2
Match value: abc at Position 6
Capture: c at Position 8
Match value: abc at Position 12
Capture: c at Position 14

关于c++ - std::match_results::size 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765512/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com