sub_match — std::sub_match
sub_match — std::sub_match
std::sub_match 클래스 템플릿은 정규식 엔진이 표시된(marked) 부분 표현식에 일치한 문자 시퀀스를 나타내는 데 사용하는 타입이에요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
match_results의 각 원소가 바로 sub_match예요.
출처: cppreference
본문
// <regex> 헤더, C++11
template< class BidirIt >
class sub_match;
일치(match)는 정규식에 일치한 대상 범위 내의 [begin, end) 쌍이에요. 다만 코드 명확성을 돕는 추가 관찰 함수(observer)들을 가져요.
주요 멤버
| 멤버 | 설명 |
|---|---|
matched |
매치가 성공했는지 (bool) |
first, second |
매치 범위 반복자 |
length() |
매치 길이 |
str() |
매치를 문자열로 |
compare(...) |
비교 |
operator==, != 등 |
비교 |
사용 예
#include <regex>
#include <iostream>
std::string s = "id: 123";
std::regex re(R"(id: (\d+))");
std::smatch m;
if (std::regex_search(s, m, re)) {
std::sub_match<std::string::const_iterator> sub = m[1];
std::cout << "값: " << sub.str() << '\n'; // 123
std::cout << "길이: " << sub.length() << '\n'; // 3
std::cout << "매치됨: " << sub.matched << '\n'; // 1
}
특징
matched == false인 경우(예: 대체 캡처 그룹이 매치 안 됨)str()은 빈 문자열,length()는 0이에요.- 문자열로 변환(
std::string)이 잘 지원돼요. match_results의operator[]결과가sub_match예요.
// 매치 안 된 그룹 처리
std::regex re2(R"((a)?b)");
std::smatch mm;
std::regex_match("b", mm, re2);
std::cout << mm[1].matched; // 0 (그룹1은 매치 안 됨)
std::cout << "[" << mm[1].str() << "]"; // []
sub_match는 정규식의 각 캡처 그룹 결과를 나타내는 기본 단위예요. .str(), .matched, .length()를 통해 개별 부분 일치를 다뤄요.