match_results — std::match_results

match_results — std::match_results

std::match_results정규식 매칭의 결과(부분 일치, sub_match들의 집합)를 담는 컨테이너예요. C++11에서 도입됐어요. <regex> 헤더에 있어요.

각 캡처 그룹의 매치 결과를 첨자로 접근할 수 있어요.

출처: cppreference

본문

// <regex> 헤더, C++11
template<
    class BidirIt,
    class Alloc = std::allocator<std::sub_match<BidirIt>>
> class match_results;

// C++17부터 pmr 버전
namespace pmr {
    template <class BidirIt>
    using match_results = std::match_results<BidirIt,
                              std::pmr::polymorphic_allocator<...>>;
}

주요 타입 별칭

별칭 타입
std::smatch match_results<string::const_iterator>
std::cmatch match_results<const char*>
std::wsmatch, std::wcmatch 와이드 문자 버전

사용 예

#include <regex>
#include <iostream>

std::string s = "year 2024";
std::regex re(R"(year (\d+))");
std::smatch m;

if (std::regex_search(s, m, re)) {
    std::cout << "전체: " << m[0] << '\n';   // "year 2024"
    std::cout << "그룹1: " << m[1] << '\n';  // "2024"
    std::cout << "개수: " << m.size() << '\n'; // 2 (전체+그룹1)
}

주요 연산

연산 설명
m[0] 전체 매치
m[i] i번째 캡처 그룹
m.size() 서브매치 개수
m.ready() 유효한지
m.prefix() 매치 앞의 시퀀스
m.suffix() 매치 뒤의 시퀀스
m.position(i) i번째 매치의 위치
m.str(i) i번째 매치를 문자열로
m.length(i) i번째 매치의 길이
m.begin(), m.end() sub_match 반복
std::regex re2(R"((\w+)=(\w+))");
std::string kv = "name=alice age=30";
auto begin = std::sregex_iterator(kv.begin(), kv.end(), re2);
for (auto it = begin; it != std::sregex_iterator{}; ++it) {
    std::smatch mm = *it;
    std::cout << mm[1] << " -> " << mm[2] << '\n';  // name->alice 등
}

match_results는 정규식 매칭의 결과(전체 매치와 각 캡처 그룹)를 구조적으로 다루는 컨테이너예요. 파싱·추출 작업에 핵심적이에요.

더 알아보기 (Learn more)

cppreference