当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ match_results length()用法及代码示例


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-th匹配的长度。

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

以下示例程序旨在说明上述函数。

程序1:

// CPP program to illustrate 
// match_results length() in C++ 
#include <bits/stdc++.h> 
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 <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; 
    return 0; 
}
输出:
max-length sub match is forgeeks with a length of 8


相关用法


注:本文由纯净天空筛选整理自Harsha_Mogali大神的英文原创作品 match_results length() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。