C++ 中的 match_results prefix() 和 suffix()


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

什麼是 C++ STL 中的 match_results?

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

什麼是 match_results::prefix()?

match_results::prefix() 函式是 C++ STL 中的內建函式,在 <regex> 標頭檔案中定義。prefix() 用於獲取與該函式關聯的物件的前序 match_results。此函式返回 match_results 物件後續序列的引用。

語法

match_results.prefix();

引數

此函式不接受任何引數。

返回值

此函式返回匹配序列之前字串或序列的常量引用。

示例

Input: string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   Mat.prefix();
Output: Tutorials

prefix()

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.prefix();
   }
   return 0;
}

輸出

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

String prefix is : Tutorials

什麼是 match_results::suffix()?

match_results::suffix() 函式是 C++ STL 中的內建函式,在 <regex> 標頭檔案中定義。suffix() 用於獲取與該函式關聯的物件的後續 match_results。此函式返回 match_results 物件後續序列的引用。

語法

match_results.suffix();

引數

此函式不接受任何引數。

返回值

此函式返回匹配序列之後字串或序列的常量引用。

示例

Input: std::string str("Tutorials Points is the best");
   std::smatch Mat;
   std::regex re("Points");
   std::regex_match ( str, Mat, re );
   Mat.suffix();
Output: is the best

suffix()

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   string str = "Tutorials Points is the best";
   regex R("Points");
   smatch Mat;
   regex_search(str, Mat, R);
   cout<<"String prefix is : ";
   if (!Mat.empty()) {
      cout << Mat.suffix();
   }
   return 0;
}

輸出

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

String prefix is : is the best

更新於:2020年3月23日

718 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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