basic_regex — std::basic_regex

basic_regex — std::basic_regex

std::basic_regex 클래스 템플릿은 정규식(regular expression)을 보관하는 일반적인 프레임워크를 제공해요. C++11에서 도입됐어요. <regex> 헤더에 있어요.

문자 타입과 특성(traits)을 매개변수로 받는 제네릭 정규식 타입이에요.

출처: cppreference

본문

// <regex> 헤더, C++11
template<
    class CharT,
    class Traits = std::regex_traits<CharT>
> class basic_regex;

멤버 타입

멤버 타입 정의
value_type CharT
traits_type Traits

문자 타입 별칭 (basic char typedefs)

별칭 타입
std::regex basic_regex<char>
std::wregex basic_regex<wchar_t>
#include <regex>
#include <iostream>

std::regex re("\\d+");        // 하나 이상의 숫자
std::string text = "abc 123 def";

std::smatch m;
if (std::regex_search(text, m, re)) {
    std::cout << m[0] << '\n';   // 123
}

생성·설정

std::regex re1("pattern");
std::regex re2;                 // 빈 패턴
re2 = R"(\w+)";                 // raw 문자열로 대입

std::regex re3("a.c", std::regex::icase);  // 옵션 지정

주요 연산

basic_regex 객체는 다음 표준 함수들과 함께 사용돼요.

  • std::regex_match전체 문자열이 패턴과 일치
  • std::regex_search부분 일치 검색
  • std::regex_replace — 일치 부분을 교체
  • std::regex_iterator, std::regex_token_iterator — 반복 일치
std::string s = "the color of the car";
std::regex re(R"((co)(l)our)");   // 캡처 그룹
std::string out = std::regex_replace(s, re, "$1$2or");  // colour → color

특징

  • 기본 문법은 ECMAScript이고, syntax_option_type으로 POSIX 기본·확장, grep 등도 선택할 수 있어요.
  • basic_regex는 소유·복사·이동이 가능해요.
std::regex re("^Hello.*$");
bool ok = std::regex_match("Hello world", re);   // true

std::basic_regex(std::regex)는 C++에서 정규표현식을 처리하는 핵심 타입이에요. 패턴 보관과 매칭 연산을 함께 제공해요.

더 알아보기 (Learn more)

cppreference