regex_iterator — std::regex_iterator
regex_iterator — std::regex_iterator
std::regex_iterator는 기본 문자 시퀀스 안에서 정규식의 개별 매치에 접근하는 읽기 전용 반복자예요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
문자열 전체에서 정규식에 일치하는 모든 부분을 순회할 때 사용해요.
출처: cppreference
본문
// <regex> 헤더, C++11
template<
class BidirIt,
class CharT = typename std::iterator_traits<BidirIt>::value_type,
class Traits = std::regex_traits<CharT>
> class regex_iterator;
사용 예
#include <regex>
#include <iostream>
std::string s = "one 2 three 44 five";
std::regex re("\\d+");
// 모든 숫자 매치 순회
auto begin = std::sregex_iterator(s.begin(), s.end(), re);
auto end = std::sregex_iterator{};
for (auto it = begin; it != end; ++it) {
std::smatch m = *it;
std::cout << m[0] << " "; // 2 44
}
특징
std::regex_iterator(또는std::sregex_iterator는string용)는 정규식에 일치하는 모든 매치를 차례로 방문해요.- 역참조(
*it)하면match_results를 얻어요. std::regex_token_iterator와 달리, 매치된 부분(sub-match)별 접근(캡처 그룹)이 가능해요.prefix()/suffix()로 매치 앞뒤도 알 수 있어요.
// 각 매치의 캡처 그룹도 접근
std::regex re2(R"((\w+)@(\w+))");
std::string emails = "[email protected] [email protected]";
for (auto it = std::sregex_iterator(emails.begin(), emails.end(), re2);
it != std::sregex_iterator{}; ++it) {
std::cout << (*it)[1] << " / " << (*it)[2] << '\n';
// a / x ...
}
regex_iterator는 텍스트에서 패턴에 일치하는 모든 위치를 반복적으로 처리해야 하는 파싱·토큰 추출 작업에 핵심적이에요.