ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของตัวดำเนินการ match_results '[ ]' ใน C++ STL
match_results ใน C++ STL คืออะไร
std::match_results เป็นคลาสที่มีลักษณะเหมือนคอนเทนเนอร์พิเศษ ซึ่งใช้เพื่อเก็บคอลเลกชันของลำดับอักขระที่ตรงกัน ในคลาสคอนเทนเนอร์นี้ การดำเนินการจับคู่ regex จะค้นหารายการที่ตรงกันของลำดับเป้าหมาย
ตัวดำเนินการ match_results คืออะไร '[ ]'
ตัวดำเนินการ Match_results [] เป็นตัวดำเนินการอ้างอิงซึ่งใช้เพื่ออ้างถึงตำแหน่งที่ i ของ match_results โดยตรง โอเปอเรเตอร์ [] ส่งกลับตำแหน่งการจับคู่ที่ i ของอ็อบเจ็กต์ที่เกี่ยวข้อง โอเปอเรเตอร์นี้มีประโยชน์เมื่อเราต้องเข้าถึงองค์ประกอบโดยตรงด้วยตำแหน่งที่ตรงกันโดยเริ่มจากศูนย์
ไวยากรณ์
match_results1[int i];
พารามิเตอร์
โอเปอเรเตอร์นี้รับ 1 พารามิเตอร์ของประเภทอินทิกรัล นั่นคือองค์ประกอบที่เราต้องการเข้าถึง
คืนค่า
ฟังก์ชันนี้จะคืนค่าการอ้างอิงไปยังตำแหน่งที่ i ของผลการแข่งขัน
ตัวอย่าง
Input: string str = "TutorialsPoint";
regex R("(Tutorials)(.*)");
smatch Mat;
regex_match(str, Mat, R);
Mat[0];
Output: TutorialsPoint ตัวอย่าง
#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 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