什么std :: match_results :: size返回? [英] What does std::match_results::size return?
问题描述
我对以下C ++ 11代码感到困惑:
I'm a bit confused about the following C++11 code:
#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个匹配项, code> size()将返回捕获组的数量和整个匹配值。
You get 1
because regex_search
returns only 1 match, and size()
will return the number of capture groups + the whole match value.
匹配是...:
Your matches
is...:
match_results type(例如cmatch或smatch),其中包含匹配结果和找到的任何子匹配的信息。
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.
如果[正则表达式搜索]成功,它不为空,并且包含一系列sub_match对象:第一个 sub_match 元素对应于整个匹配,如果正则表达式包含要匹配的子表达式(即,括号 - 分隔的组),则其对应的子匹配作为连续的子匹配元素存储在match_results中对象。
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.
这里是一个可以找到多个匹配的代码:
Here is a code that will find multiple matches:
#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演示返回 abc
3次。
输入字符串,这里是基于 std :: sregex_iterator
( std :: wsregex_iterator
subject是 std :: wstring
对象):
As this method destroys the input string, here is another alternative based on the std::sregex_iterator
(std::wsregex_iterator
should be used when your subject is an std::wstring
object):
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演示,返回
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
这篇关于什么std :: match_results :: size返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!