Namespaces
Variants

std::match_results<BidirIt,Alloc>:: format

From cppreference.net
Regular expressions library
Classes
(C++11)
Algorithms
Iterators
Exceptions
Traits
Constants
(C++11)
Regex Grammar
template < class OutputIt >

OutputIt format ( OutputIt out,
const char_type * fmt_first, const char_type * fmt_last,
std:: regex_constants :: match_flag_type flags =

std:: regex_constants :: format_default ) const ;
(1) (自 C++11 起)
template < class OutputIt, class ST, class SA >

OutputIt format ( OutputIt out,
const basic_string < char_type,ST,SA > & fmt,
std:: regex_constants :: match_flag_type flags =

std:: regex_constants :: format_default ) const ;
(2) (自 C++11 起)
template < class ST, class SA >

std:: basic_string < char_type,ST,SA >
format ( const std:: basic_string < char_type,ST,SA > & fmt,
std:: regex_constants :: match_flag_type flags =

std:: regex_constants :: format_default ) const ;
(3) (自 C++11 起)
string_type format ( const char_type * fmt_s,

std:: regex_constants :: match_flag_type flags =

std:: regex_constants :: format_default ) const ;
(4) (自 C++11 起)

format 输出格式化字符串,将该字符串中的任何格式说明符或转义序列替换为来自 * this 的匹配数据。

1) 格式字符序列由范围 [ fmt_first , fmt_last ) 定义。生成的字符序列将被复制到 out
2) 格式字符序列由 fmt 中的字符定义。生成的字符序列将被复制到 out
3,4) 格式字符序列分别由 fmt fmt_s 中的字符定义。生成的字符序列将被复制到新构造的 std::basic_string 中并返回。

flags 位掩码决定了识别哪些格式说明符和转义序列。

format ready ( ) ! = true 时,其行为是未定义的。

目录

参数

fmt_begin, fmt_end - 指向定义格式字符序列的字符范围起始与结束的指针
fmt - std::basic_string 定义格式字符序列
fmt_s - 指向定义格式字符序列的以空字符结尾的字符串指针
out - 结果字符序列被复制到的迭代器
flags - std::regex_constants::match_flag_type 位掩码,指定识别的格式说明符和转义序列
类型要求
-
OutputIt 必须满足 LegacyOutputIterator 的要求。

返回值

1,2) out
3,4) 包含结果字符序列的新构造字符串。

异常

可能抛出实现定义的异常。

示例

#include <iostream>
#include <regex>
#include <string>
int main()
{
    std::string s = "for a good time, call 867-5309";
    std::regex phone_regex("\\d{3}-\\d{4}");
    std::smatch phone_match;
    if (std::regex_search(s, phone_match, phone_regex))
    {
        std::string fmt_s = phone_match.format(
            "$`"   // $` 表示匹配项前的字符
            "[$&]" // $& 表示匹配的字符
            "$'"); // $' 表示匹配项后的字符
        std::cout << fmt_s << '\n';
    }   
}

输出:

for a good time, call [867-5309]

参见

使用格式化替换文本替换正则表达式的匹配项
(函数模板)
匹配专用的选项
(类型定义)