regex_search — std::regex_search
regex_search — std::regex_search
std::regex_search는 대상 시퀀스에서 정규식에 부분적으로 일치하는 것이 있는지 검사하는 함수예요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
regex_match(전체 일치)와 달리 부분 일치를 찾아요.
출처: cppreference
본문
// <regex> 헤더, C++11
template< class BidirIt, class Alloc, class CharT, class Traits >
bool regex_search( BidirIt first, BidirIt last,
std::match_results<BidirIt, Alloc>& m,
const std::basic_regex<CharT, Traits>& e,
std::regex_constants::match_flag_type flags =
std::regex_constants::match_default );
사용 예
#include <regex>
#include <iostream>
std::string s = "The secret code is 12345";
std::regex re("\\d+");
std::smatch m;
if (std::regex_search(s, m, re)) {
std::cout << "첫 매치: " << m[0] << '\n'; // 12345
}
전체 vs 부분 일치
std::regex re2("abc");
std::regex_search("xabcx", re2); // true (부분 일치)
std::regex_match("xabcx", re2); // false (전체 불일치)
캡처 그룹과 위치
std::string s2 = "id=42 age=30";
std::regex re3(R"((\w+)=(\d+))");
std::smatch mm;
if (std::regex_search(s2, mm, re3)) {
std::cout << mm[1] << "=" << mm[2] << '\n'; // id=42
std::cout << "위치: " << mm.position() << '\n';
}
특징
- 처음 일치하는 위치만 찾아요. 모든 매치를 순회하려면
regex_iterator를 사용해요. - 형식 내 포함 여부 확인, 키워드 검색 등에 주로 사용돼요.
- 문자열 오버로드
std::regex_search(s, re)도 있어요.
// 포함 여부만 빠르게
if (std::regex_search("received email", std::regex("email"))) {
// ...
}
regex_search는 문자열 안에 특정 패턴이 존재하는지 검사하는 표준 방법이에요. 검색·유효성 확인에 널리 쓰여요.