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 进行目标字符序列的替换:
[
first,
last)
中的字符到 out,以 fmt 所格式化的字符替换任何匹配 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 = /* 替换表达式 */ } 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::basic_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"); // 写结果到输出迭代器 std::regex_replace(std::ostreambuf_iterator<char>(std::cout), text.begin(), text.end(), vowel_re, "*"); // 构造保有结果的字符串 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++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 2213 | C++11 | 替换操作不会更新 out | 会更新 out |
[编辑] 参阅
(C++11) |
尝试匹配一个正则表达式到字符序列的任何部分 (函数模板) |
(C++11) |
特定于匹配的选项 (typedef) |
替换字符串的指定部分 ( std::basic_string<CharT,Traits,Allocator> 的公开成员函数)
|