match_results::operator []是C++中的內置函數,用於獲取match_result對象中的i-th匹配項。它為操作員內部指定位置的匹配提供參考。
用法:
smatch_name[N] Note:smatch_name is an object of match_results class.
參數:它接受一個指定匹配編號的參數N。它小於match_results::size。匹配數字0表示整個匹配表達式。後續的匹配數字標識子表達式(如果有)。傳遞的積分是無符號積分類型。
返回值:它在N-th匹配處返回對該匹配的直接引用。
注意:第一個元素始終包含整個正則表達式匹配項,而其他元素則包含特定的捕獲組。
以下示例程序旨在說明上述函數。
程序1:
// CPP program to illustrate
// match_results operator[] in C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s("Geeksforgeeks");
regex re("(Geeks)(.*)");
smatch match;
regex_match(s, match, re);
// use of operator[]--> returns the
// reference to the match at i-th position
cout << "Matches are:" << endl;
for (int i = 0; i < match.size(); i++) {
cout << "match " << i << " is " << match[i] << endl;
}
}
輸出:
Matches are: match 0 is Geeksforgeeks match 1 is Geeks match 2 is forgeeks
程序2:
// CPP program to illustrate
// match_results operator[] in C++
// Find maximum length
#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 << endl;
return 0;
}
輸出:
max-length sub match is forgeeks with a length of 8
相關用法
- C++ map::operator[]用法及代碼示例
- C++ unordered_map operator[]用法及代碼示例
- C++ forward_list::operator=用法及代碼示例
- C++ list::operator=用法及代碼示例
- C++ array::operator[]用法及代碼示例
注:本文由純淨天空篩選整理自Harsha_Mogali大神的英文原創作品 match_results operator[] in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。