regex_replace 函数

replaces 匹配正则表达式。

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
    元素的字符类。

  • Alloc
    正则表达式分配程序类。

  • Elem
    元素类型与匹配。

  • flags
    匹配的标志。

  • first
    序列开始要匹配的。

  • fmt
    替换的格式。

  • last
    序列末尾为匹配的。

  • out
    输出迭代器。

  • re
    要匹配的正则表达式。

  • str
    要匹配的字符串。

备注

第一构造函数 regex_iterator 类 对象的 iter(first, last, re, flags) 并使用它将其输入值域 [first, last) 为一系列不同 T0M0T1M1...TN-1MN-1TN,Mn 检测是迭代器的 nth 匹配。 如果找不到任何匹配,T0 是整个输入范围,并且 N 为零。 如果只使用与第一个 (flags & format_first_only) != 0,T1 是遵循任何输入匹配的文本,因此,N 是 1。 对于范围在 [0, N)中的每个 i,(flags & format_no_copy) == 0,则其副本。范围 Ti 的文本对迭代器 out。 然后调用 m.format(out, fmt, flags),m 是 subsequence 的 Mi迭代器对象返回的 match_results 对象的 iter。 最后,(flags & format_no_copy) == 0,则其副本。范围 TN 的文本对迭代器 out。 函数返回 out。

第二个函数局部变量 result 类型构造 basic_string<charT> 并调用 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::regex rx("a"); 
    std::string fmt("A"); 
    std::regex_constants::match_flag_type fonly = 
        std::regex_constants::format_first_only; 
 
    *std::regex_replace(&buf[0], first, last, rx, fmt) = '\0'; 
    std::cout << "replacement == " << &buf[0] << std::endl; 
 
    *std::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::regex_replace(str, rx, fmt) << std::endl; 
 
    std::cout << "replacement == " 
        << std::regex_replace(str, rx, fmt, fonly) << std::endl; 
 
    return (0); 
    } 
 
  

要求

标头: <regex>

命名空间: std

请参见

参考

<regex>

regex_match 函数

regex_search 函数