std::regex_replace
| ヘッダ <regex> で定義 |
||
| template< class OutputIt, class BidirIt, class Traits, class CharT, class STraits, class SAlloc > |
(1) | (C++11以降) |
| template< class OutputIt, class BidirIt, class Traits, class CharT > OutputIt regex_replace( OutputIt out, BidirIt first, BidirIt last, |
(2) | (C++11以降) |
| template< class Traits, class CharT, class STraits, class SAlloc, class FTraits, class FAlloc > |
(3) | (C++11以降) |
| template< class Traits, class CharT, class STraits, class SAlloc > std::basic_string<CharT, STraits, SAlloc> |
(4) | (C++11以降) |
| template< class Traits, class CharT, class STraits, class SAlloc > std::basic_string<CharT> |
(5) | (C++11以降) |
| template< class Traits, class CharT > std::basic_string<CharT> |
(6) | (C++11以降) |
regex_replace は、正規表現 re を使用して、対象の文字シーケンスに対して置換を実行します。
using iter_type = std::regex_iterator<BidirIt, CharT, Traits>; iter_type seq_begin(first, last, re, flags), seq_end; using result_type = std::match_results<BidirIt>; result_type m; bool need_to_copy = (flags & std::regex_constants::format_no_copy) == 0; bool format_all = (flags & std::regex_constants::format_first_only) != 0; for (iter_type i = seq_begin; i != seq.end(); ++i) { m = *i; if (need_to_copy) out = std::copy(m.prefix().first, m.prefix().second, out); if (format_all || i == seq_begin) out = /* replace-expr */ } if (need_to_copy) out = m.ready() ? std::copy(m.suffix().first, m.suffix().second, out) : std::copy(first, last, out); return out;
regex_replace(std::back_inserter(result),
str.begin(), str.end(), re, fmt, flags);
return result;。
regex_replace(std::back_inserter(result),
s, s + std::char_traits<CharT>::length(s), re, fmt, flags);
return result;。
目次 |
[編集] パラメータ
| first, last | - | 対象の文字範囲 |
| str | - | 対象の std::string |
| s | - | 対象のヌル終端Cスタイルの文字列 |
| re | - | 正規表現 |
| fmt | - | flags の値によって構文が異なる、正規表現置換フォーマット文字列。 |
| flags | - | 一致の実行方法を決定するために使用されるフラグ |
| out | - | 置換結果を格納するための出力イテレータ。 |
[編集] 戻り値
上記の通り。
[編集] 例外
エラー条件を示すために std::regex_error を送出する可能性があります。
[編集] 例
#include <iostream> #include <iterator> #include <regex> #include <string> int main() { std::string text = "Quick brown fox"; std::regex vowel_re("a|e|i|o|u"); // write the results to an output iterator std::regex_replace(std::ostreambuf_iterator<char>(std::cout), text.begin(), text.end(), vowel_re, "*"); // construct a string holding the results std::cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << '\n'; }
出力
Q**ck br*wn f*x Q[u][i]ck br[o]wn f[o]x
[編集] 不具合報告
以下の動作変更を伴う欠陥報告が、以前に公開されたC++標準に遡って適用されました。
| DR | 適用対象 | 公開された動作 | 正しい動作 |
|---|---|---|---|
| LWG 2213 | C++11 | out は置換によって更新されていませんでした。 | out は更新されます。 |
[編集] 関連項目
| (C++11) |
正規表現を文字シーケンスの任意の部分にマッチさせようと試みる (関数テンプレート) |
| (C++11) |
マッチングに特化したオプション (typedef) |
| 文字列の指定された部分を置換する ( std::basic_string<CharT,Traits,Allocator> のメンバ関数) |