ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของ match_results operator [] ใน C++ STL
match_results ใน C++ STL คืออะไร?
std::match_results เป็นคลาสคล้ายคอนเทนเนอร์เฉพาะทาง ที่ใช้เก็บคอลเลกชันของลำดับตัวอักษรที่จับคู่ได้ ในคลาสนี้ regex match operation หา matches ของ target sequence
match_results operator [] คืออะไร?
Match_results operator [] เป็น reference operator ใช้อ้างอิงตำแหน่ง i-th ของ match_results โดยตรง คืนค่า i-th match position ของ object ที่เกี่ยวข้อง ใช้สะดวกเมื่อต้องการเข้าถึง element โดย match position เริ่มจาก 0
ไวยากรณ์
match_results1[int i];
พารามิเตอร์
Operator รับพารามิเตอร์ 1 ตัว คือ integral type คือตำแหน่ง element ที่ต้องการเข้าถึง
ค่าที่คืน
คืนค่า reference ไปยัง i-th location ของ match result
ตัวอย่าง
Input: string str = "TutorialsPoint"; regex R("(Tutorials)(.*)"); smatch Mat; regex_match(str, Mat, R); Mat[0]; Output: TutorialsPoint
ตัวอย่างโค้ด 1
#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
ตัวอย่างโค้ด 2
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "Tutorials Point";
regex R("(Tutorials)(Point)(.*)");
smatch Mat;
regex_match(str, Mat, R);
int len = 0;
string S;
for(int i = 1; i < Mat.size(); i++) {
if(Mat.length(i) > len) {
str = Mat[i];
len = Mat.length(i);
}
}
cout << "Matching length is : " << len << endl;
return 0;
}
เอาต์พุต
Matching length is : 0