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.