이 글에서는 C++ STL에서 match_results 연산자 '='의 동작 방식, 구문 그리고 실제 예제에 대해 자세히 알아보겠습니다.
C++ STL에서 match_results란 무엇인가?
std::match_results는 정규식(regex) 매칭 작업으로 찾은 문자 시퀀스들의 집합을 저장하는 특수한 컨테이너 유사 클래스입니다. 이 컨테이너 클래스 내부에서 정규식 매치 연산이 수행되며, 대상 시퀀스에서 일치하는 부분들을 찾아 저장하게 됩니다.
match_results 연산자 '='란 무엇인가?
match_results 연산자 =는 match_results 객체에 값을 할당하는 데 사용되는 대입 연산자입니다. 이 연산자를 활용하면 한 match_results 객체의 요소들을 다른 객체로 복사(copy)하거나 이동(move)할 수 있습니다.
구문
match_results1 = (match_results2);
매개변수
match_results 객체로 복사할 데이터를 담고 있는 또 다른 match_results 객체입니다.
반환 값
이 연산자는 아무 값도 반환하지 않습니다(void).
예제 1: 기본적인 대입 연산
입력: string str = "Tutorials Point";
regex R("(Tutorials)(.*)");
smatch Mat_1, Mat_2;
regex_match(str, Mat_1, R);
Mat_2 = Mat_1;
출력: MAT 2 =
Tutorials Point
Tutorials
Point
예제 코드
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "Tutorials Point";
regex R("(Tutorials)(.*)");
smatch Mat_1, Mat_2;
regex_match(str, Mat_1, R);
Mat_2 = Mat_1;
cout<<"String matches: " << endl;
for (smatch::iterator i = Mat_2.begin(); i!= Mat_2.end(); i++) {
cout << *i << endl;
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
String matches:
Tutorials Point
Tutorials
Point
예제 2: 조건문과 함께 사용하기
다음 예제에서는 두 개의 서로 다른 정규식으로 매칭한 결과 중 크기가 더 큰 쪽을 선택하여 대입 연산자로 새로운 객체에 할당하는 방법을 보여줍니다.
#include <bits/stdc++.h>
using namespace std;
int main() {
string str = "Tutorials Point";
regex R_1("(Tutorials)(.*)");
regex R_2("(Po)(int)(.*)");
smatch Mat_1, Mat_2;
regex_match(str, Mat_1, R_1);
regex_match(str, Mat_2, R_2);
smatch Mat;
if (Mat_1.size() > Mat_2.size()) {
Mat = Mat_1;
} else {
Mat = Mat_2;
}
cout<<"string matches " << endl;
for (smatch::iterator i = Mat.begin(); i!= Mat.end(); i++) {
cout << *i << endl;
}
}
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다 −
String matches:
Tutorials Point
Tutorials
Point
정리
match_results 연산자 =는 정규식 매칭 결과를 다른 객체에 손쉽게 복사하거나 이동할 수 있게 해주는 편리한 도구입니다. 조건문과 함께 활용하면 여러 매칭 결과 중 원하는 것을 유연하게 선택할 수 있어, 정규식 기반 문자열 처리 로직을 더욱 깔끔하게 작성할 수 있습니다.