regex_error — std::regex_error
regex_error — std::regex_error
std::regex_error는 정규식 라이브러리에서 오류를 보고하기 위해 던져지는 예외 객체의 타입이에요. C++11에서 도입됐어요. <regex> 헤더에 있어요.
잘못된 정규식 패턴이나 매칭 오류 시 던져져요.
출처: cppreference
본문
// <regex> 헤더, C++11
class regex_error;
std::regex_error는 std::regex_constants::error_type(오류 코드)을 담는 std::runtime_error 파생 예외예요.
멤버 함수
| 함수 | 설명 |
|---|---|
regex_error(error_type) |
생성자 — 오류 코드 지정 |
code() |
error_type 오류 코드 반환 |
사용 예
#include <regex>
#include <iostream>
try {
std::regex re("[unclosed"); // 잘못된 패턴
} catch (const std::regex_error& e) {
std::cout << "오류 코드: "
<< static_cast<int>(e.code()) << '\n';
std::cout << "설명: " << e.what() << '\n';
}
표준 오류 처리에서 몇 가지 경우에 던져질 수 있어요.
- 잘못된 정규식 패턴을
std::regex로 컴파일할 때 - 매칭이 너무 복잡해서(
error_complexity) 처리할 수 없을 때 - 스택 한계 초과(
error_stack) 등
// 복잡도 오류 예
try {
std::regex re("(a+)+$");
std::string evil = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!";
std::regex_search(evil, std::smatch{}, re); // ReDoS 가능
} catch (const std::regex_error& e) {
if (e.code() == std::regex_constants::error_complexity)
std::cout << "복잡도 초과\n";
}
regex_error는 정규식 사용 시 오류를 잡아 진단하는 표준 방법이에요. .code()로 구체적인 오류 종류를 알 수 있어요.