📜  C++ STL中的match_results length()

📅  最后修改于: 2021-05-30 07:54:27             🧑  作者: Mango

match_results :: length()是C++中的内置函数,用于返回match_results对象中特定匹配项的长度。

句法:

smatch_name.length(n)

Note: smatch_name is an object of match_results class.

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

返回值:返回match_results对象中第n个匹配项的长度。

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

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

程序1:

// CPP program to illustrate
// match_results length() in C++
#include 
using namespace std;
  
int main()
{
    string s("Geeksforgeeks");
    regex re("(Geeks)(.*)");
  
    smatch match;
  
    regex_match(s, match, re);
  
    for (int i = 0; i < match.size(); i++) {
        cout << "match " << i << " has a length of "
             << match.length(i) << endl;
    }
    return 0;
}
输出:
match 0 has a length of 13
match 1 has a length of 5
match 2 has a length of 8

程式2:

// CPP program to illustrate
// match_results length() in C++
#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;
    return 0;
}
输出:
max-length sub match is forgeeks with a length of 8
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”