📜  C++ STL中的match_results运算符[]

📅  最后修改于: 2021-05-30 04:21:36             🧑  作者: Mango

match_results ::运算符[]是C++中的内置函数,用于在match_result对象中获取第i个匹配项。它为运算符内部指定位置的匹配提供参考。

句法:

smatch_name[N]

Note: smatch_name is an object of match_results class.

参数:它接受一个指定匹配编号的参数N。它低于match_results :: size。匹配数字0表示整个匹配表达式。后续的匹配数字标识子表达式(如果有)。传递的积分是无符号积分类型。

返回值:返回对第N个匹配项的直接引用。

注意:第一个元素始终包含整个正则表达式匹配项,而其他元素则包含特定的捕获组。

下面的程序说明了上述函数。
程序1:

// CPP program to illustrate
// match_results operator[] in C++
#include 
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 
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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”