regex_match — std::regex_match
regex_match — std::regex_match
std::regex_match는 대상 시퀀스 전체가 정규식에 일치하는지 검사하는 함수예요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
regex_search(부분 일치)와 달리 전체 일치만 검사해요.
출처: cppreference
본문
// <regex> 헤더, C++11
template< class BidirIt, class Alloc, class CharT, class Traits >
bool regex_match( 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::regex re("\\d{4}-\\d{2}-\\d{2}"); // 날짜 형태
std::cout << std::regex_match("2024-01-15", re); // true
std::cout << std::regex_match("date 2024-01-15", re); // false (부분만 일치)
// 매치 결과(캡처 그룹)도 받기
std::regex re2(R"((\w+)-(\w+))");
std::smatch m;
std::string s = "foo-bar";
if (std::regex_match(s, m, re2)) {
std::cout << m[1] << " " << m[2] << '\n'; // foo bar
}
regex_match vs regex_search
regex_match— 문자열 전체가 패턴과 일치해야 true.regex_search— 문자열 일부라도 패턴과 일치하면 true.
std::regex re3("abc");
std::regex_match("xabcx", re3); // false (전체 불일치)
std::regex_search("xabcx", re3); // true (부분 일치)
특징
- 형식 검증(이메일, 날짜, ID 등)에 주로 사용돼요.
match_results를 넘기면 캡처 그룹 결과도 얻을 수 있어요.- 문자열 오버로드(
std::regex_match(s, re))도 있어요.
// 문자열 오버로드
bool valid = std::regex_match("123", std::regex("\\d+"));
regex_match는 입력이 특정 패턴 형식과 정확히 일치하는지 확인하는 검증 작업에 필수적이에요.