Programming/c++

[c++] regex_replace 함수

owls 2023. 1. 20. 13:24
728x90

1.함수 헤더 파일

#include <regex>

2.함수 원형

template <class OutIt, class BidIt, class RXtraits, class Alloc, class Elem>
OutIt regex_replace(
    OutIt out,
    BidIt first,
    BidIt last,
    const basic_regex<Elem, RXtraits, Alloc>& re,
    const basic_string<Elem>& fmt,
    match_flag_type flags = match_default);

template <class RXtraits, class Alloc, class Elem>
basic_string<Elem> regex_replace(
    const basic_string<Elem>& str,
    const basic_regex<Elem, RXtraits, Alloc>& re,
    const basic_string<Elem>& fmt,
    match_flag_type flags = match_default);

 

3. Parameter(매개 변수)

OutIt The iterator type for replacement.
BidIt The iterator type for submatches.
RXtraits The attribute class for the element.
Alloc The regular expression allocator class.
Elem The type of element to find a match for.
flags Flags for matching.
first The start of the matching sequence.
fmt The format for substitution.
last End of matching sequence.
out An output iterator.
re The regular expression to look for matches.
str A string to match.

 

4. Described

첫 번째 함수는 클래스 객체 iter(first, last, re, flags)를 구성하고, 'regex_iterator'를 사용하여  [first, last)입력 범위를 T0 M0 T1 M1...TN-1 MN-1 TN 로 분할합니다. 

여기서 MN은 match가 발견되는 n번째 iterator입니다. 일치하는 항목이 발견되지 않으면 은 전체 입력 범위이고 N은 0입니다. (timeout & format_first_only)!= 0.

 

 

4.예제

#include <iostream>
#include <regex>

using namespace std;
int main(){
	string str("adaeaf");
    regex rx("a");
    string fmt("A");
    cout << "relpacement == " << regex_replace(str, rx, fmt) << endl; 

    regex_constants::match_flag_type fonly = regex_constants::format_first_only;
    cout << "replacement == " << regex_replace(str, rx ,fmt, fonly) << endl;
    
	return 0;
}
relpacement == AdAeAf   // 매치되는 모든 문자 replacement
replacement == Adaeaf   // 첫번째 매치되는 문자만 replacement

 

728x90