regex_replace — std::regex_replace
regex_replace — std::regex_replace
std::regex_replace는 정규식에 일치하는 부분을 교체(replacement) 문자열로 바꾸는 함수예요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
일치 부분을 fmt 포맷으로 치환한 결과를 만들어요.
출처: cppreference
본문
// <regex> 헤더, C++11
template< class OutputIt, class BidirIt, class Traits, class CharT,
class STraits, class SAlloc >
OutputIt regex_replace( OutputIt out, BidirIt first, BidirIt last,
const std::basic_regex<CharT, Traits>& re,
const std::basic_string<CharT, STraits, SAlloc>& fmt,
... );
사용 예
#include <regex>
#include <iostream>
std::string s = "apple 123 banana 456";
std::regex re("\\d+");
// 모든 숫자를 "N"으로 교체
std::string r = std::regex_replace(s, re, "N");
// "apple N banana N"
캡처 그룹 참조
fmt에서 $1, $2, $& 등으로 캡처 그룹을 참조할 수 있어요.
std::string s2 = "colour color";
std::regex re2(R"((col)(o)ur)");
// "colour" → $1 + "о" + "r"... 실제로는 아래 참조 사용
std::string r2 = std::regex_replace(s2, re2, "$1or");
// "color color"
// 전체 매치 참조
std::string r3 = std::regex_replace("a-b-c", std::regex("-"), "[$&]");
// "a[-]b[-]c"
특징
- 기본적으로 일치하는 모든 부분을 교체해요.
- 옵션으로 일치하지 않는 부분 보존/제거를 제어할 수 있어요.
- 간편한 문자열 반환 오버로드
std::regex_replace(s, re, fmt)도 있어요.
// 숫자만 마스킹
std::string phone = "Call 010-1234-5678";
std::string masked = std::regex_replace(phone, std::regex("\\d"), "*");
// "Call ***-****-****"
regex_replace는 텍스트 변환·정리·마스킹·포맷 변경 등에서 널리 쓰이는 함수예요.