C++ STL 中 match_results 的 length() 函式


在本文中,我們將討論 C++ STL 中 match_results::length() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 match_results?

std::match_results 是一個專門的類似容器的類,用於儲存匹配到的字元序列集合。在這個容器類中,正則表示式匹配操作查詢目標序列的匹配項。

什麼是 match_results::length()?

match_results::length() 函式是 C++ STL 中的內建函式,定義在 <regex> 標頭檔案中。length() 用於檢查與之關聯的 match_results 物件中第 n 個匹配項的長度。length() 接受一個引數,即匹配編號,該編號應小於 match_results::size(),用於檢查第 n 個匹配項的長度。

語法

smatch_name.length(unsigned int num);

引數

此函式接受一個引數,即匹配編號,該編號應小於容器的大小。匹配編號 0 代表整個匹配表示式。

返回值

此函式返回物件中匹配項數量的無符號整數值。

示例

Input: std::smatch;
   smatch.length(0);
Output: 0

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "TutorialsPoint";
   regex R("(Tutorials)(.*)");
   smatch Mat;
   regex_match(str, Mat, R);
   for (int i = 0; i < Mat.size(); i++) {
      cout<<"Match is : " << Mat[i]<< endl;
   }
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

Match is : TutorialsPoint
Match is : Tutorials
Match is : Point

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   string sr = "Tutorials Point";
   regex Re("(Tutorials)(.*)");
   smatch Mat;
   regex_match(sr, Mat, Re);
   int len = 0;
   string str;
   for (int i = 1; i < Mat.size(); i++) {
      if (Mat.length(i) > len) {
         str = Mat[i];
         len = Mat.length(i);
      }
   }
   cout<<"Match length is of: " << len;
   return 0;
}

輸出

如果執行以上程式碼,將生成以下輸出:

Match length is of: 9

更新於:2020年3月23日

77 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.