regex_replace 関数
更新 : 2007 年 11 月
一致した正規表現を置換します。
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);
パラメータ
OutIt
置換の反復子の型。BidIt
サブマッチの反復子の型。RXtraits
要素の特徴 (traits) クラス。Alloc
正規表現のアロケータ クラス。Elem
一致させる要素の型。flags
一致のフラグ。first
一致させるシーケンスの最初。fmt
置換の形式。last
一致させるシーケンスの最後。out
出力反復子。re
一致させる正規表現。str
一致させる文字列。
解説
1 つ目の関数は、regex_iterator クラス オブジェクト iter(first, last, re, flags) を構築し、それを使って入力範囲 [first, last) を一連のサブシーケンス T0M0T1M1...TN-1MN-1TN に分割します (Mn は、反復子によって検出された nth で示される順位の一致)。一致が見つからなかった場合、T0 は入力範囲全体になり、N は 0 になります。(flags & format_first_only) != 0 の場合、最初の一致だけが使用され、T1 は一致に続くすべての入力テキストになり、N は 1 になります。範囲 [0, N) 内の各 i について、(flags & format_no_copy) == 0 の場合は、範囲 Ti 内のテキストが反復子 out にコピーされます。次に、m.format(out, fmt, flags) が呼び出されます。m は、サブシーケンス Mi の反復子オブジェクト iter により返された match_results オブジェクトです。最後に、(flags & format_no_copy) == 0 の場合は、範囲 TN 内のテキストが反復子 out にコピーされます。この関数は、out を返します。
2 つ目の関数は、basic_string<charT> 型のローカル変数 result を構築し、regex_replace(back_inserter(result), str.begin(), str.end(), re, fmt, flags) を呼び出します。result が返されます。
使用例
// std_tr1__regex__regex_replace.cpp
// compile with: /EHsc
#include <regex>
#include <iostream>
int main()
{
char buf[20];
const char *first = "axayaz";
const char *last = first + strlen(first);
std::tr1::regex rx("a");
std::string fmt("A");
std::tr1::regex_constants::match_flag_type fonly =
std::tr1::regex_constants::format_first_only;
*std::tr1::regex_replace(&buf[0], first, last, rx, fmt) = '\0';
std::cout << "replacement == " << &buf[0] << std::endl;
*std::tr1::regex_replace(&buf[0], first, last, rx, fmt, fonly) = '\0';
std::cout << "replacement == " << &buf[0] << std::endl;
std::string str("adaeaf");
std::cout << "replacement == "
<< std::tr1::regex_replace(str, rx, fmt) << std::endl;
std::cout << "replacement == "
<< std::tr1::regex_replace(str, rx, fmt, fonly) << std::endl;
return (0);
}
replacement == AxAyAz
replacement == Axayaz
replacement == AdAeAf
replacement == Adaeaf
必要条件
ヘッダー : <regex>
名前空間 : std::tr1