std::regex_replace
| 定义于头文件 <regex>
|
||
| template< class OutputIt, class BidirIt, class Traits, class CharT, |
(1) | (C++11 起) |
| template< class OutputIt, class BidirIt, class Traits, class CharT > |
(2) | (C++11 起) |
| template< class Traits, class CharT, class STraits, class SAlloc, |
(3) | (C++11 起) |
| template< class Traits, class CharT, class STraits, class SAlloc > |
(4) | (C++11 起) |
| template< class Traits, class CharT, class STraits, class SAlloc > |
(5) | (C++11 起) |
| template< class Traits, class CharT > std::basic_string<CharT> |
(6) | (C++11 起) |
regex_replace 用正则表达式进行字符序列的替换:
[first,last) 中的字符到 out ,以 re 所格式化的字符替换任何匹配 fmt 的序列。换言之:- 如同以 std::regex_iterator<BidirIt, CharT, traits> i(first, last, re, flags) 构造 std::regex_iterator 对象
i,并用它在序列[first,last)内前进通过每个re的匹配。 - 对于每个匹配
m,如同用 out = std::copy(m.prefix().first, m.prefix().second, out) 复制非匹配子序列(m.prefix())到out,然后如同通过调用 out = m.format(out, fmt, flags) ,以格式化替换字符串替换匹配的子序列。 - 找不到更多匹配时,如同用 out = std::copy(last_m.suffix().first, last_m.suffix().second, out) 复制剩余的非匹配字符到
out,其中last_m是找到的最后匹配的副本。 - 若无匹配,则原态地复制整个序列到
out,以 out = std::copy(first, last, out) 。 - 若
flags含有 std::regex_constants::format_no_copy ,则不复制非匹配的子序列到out。 - 若
flags含有 std::regex_constants::format_first_only ,则只替换首个匹配。
- 如同以 std::regex_iterator<BidirIt, CharT, traits> i(first, last, re, flags) 构造 std::regex_iterator 对象
result ,并调用 std::regex_replace(std::back_inserter(result), s.begin(), s.end(), re, fmt, flags) 。result 并调用 std::regex_replace(std::back_inserter(result), s, s + std::char_traits<CharT>::length(s), re, fmt, flags) 。目录 |
[编辑] 参数
| first, last | - | 以一对迭代器表示的输入字符序列 |
| s | - | 以 std::basic_string 或字符数组表示的输入字符序列 |
| re | - | 将与输入序列匹配的 std::basic_regex |
| flags | - | std::regex_constants::match_flag_type 类型的匹配标志 |
| fmt | - | 正则表达式替换格式字符串,准确语法依赖于 flags 的值
|
| out | - | 存储替换结果的输出迭代器 |
| 类型要求 | ||
-OutputIt 必须满足 OutputIterator 的要求。
| ||
-BidirIt 必须满足 BidirectionalIterator 的要求。
| ||
[编辑] 返回值
out 在所有插入后的副本。result 。[编辑] 异常
可能抛出指示错误条件的 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++11) |
试图匹配正则表达式到字符序列的任何部分 (函数模板) |
| (C++11) |
特定到匹配的选项 (typedef) |