match_results::operator []是C++中的内置函数,用于获取match_result对象中的i-th匹配项。它为操作员内部指定位置的匹配提供参考。
用法:
smatch_name[N] Note:smatch_name is an object of match_results class.
参数:它接受一个指定匹配编号的参数N。它小于match_results::size。匹配数字0表示整个匹配表达式。后续的匹配数字标识子表达式(如果有)。传递的积分是无符号积分类型。
返回值:它在N-th匹配处返回对该匹配的直接引用。
注意:第一个元素始终包含整个正则表达式匹配项,而其他元素则包含特定的捕获组。
以下示例程序旨在说明上述函数。
程序1:
// CPP program to illustrate
// match_results operator[] in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s("Geeksforgeeks");
regex re("(Geeks)(.*)");
smatch match;
regex_match(s, match, re);
// use of operator[]--> returns the
// reference to the match at i-th position
cout << "Matches are:" << endl;
for (int i = 0; i < match.size(); i++) {
cout << "match " << i << " is " << match[i] << endl;
}
}
输出:
Matches are: match 0 is Geeksforgeeks match 1 is Geeks match 2 is forgeeks
程序2:
// CPP program to illustrate
// match_results operator[] in C++
// Find maximum length
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s("Geeksforgeeks");
regex re("(Ge)(eks)(.*)");
smatch match;
regex_match(s, match, re);
int max_length = 0;
string str;
// Since the first match is the whole string we do not consider it.
for (int i = 1; i < match.size(); i++) {
if (match.length(i) > max_length) {
str = match[i];
max_length = match.length(i);
}
}
cout << "max-length sub match is " << str
<< " with a length of " << max_length << endl;
return 0;
}
输出:
max-length sub match is forgeeks with a length of 8
相关用法
- C++ map::operator[]用法及代码示例
- C++ unordered_map operator[]用法及代码示例
- C++ forward_list::operator=用法及代码示例
- C++ list::operator=用法及代码示例
- C++ array::operator[]用法及代码示例
注:本文由纯净天空筛选整理自Harsha_Mogali大神的英文原创作品 match_results operator[] in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。