當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。