Search⌘ K

Format

Explore how to format text in C++ with std::regex_replace and std::match_results.format using capture groups and special escape sequences. Understand different formatting strategies to extract and replace matched text accurately, preparing you for advanced text processing with regular expressions.

We'll cover the following...

std::regex_replace and std::match_results.format, in combination with capture groups enable us to format text. We can use a format string together with a placeholder to insert the value.

Here are both possibilities:

C++
#include <regex>
#include <iomanip>
#include <iostream>
#include <string>
int main(){
std::cout << std::endl;
std::string future{"Future"};
int len= sizeof(future);
const std::string unofficial{"unofficial, C++0x"};
const std::string official{"official, C++11"};
std::regex regValues{"(.*), (.*)"};
std::string standardText{"The $1 name of the new C++ standard is $2."};
// using std::regex_replace
std::string textNow= std::regex_replace(unofficial, regValues, standardText );
std::cout << std::setw(len) << std::left << "Now: " << textNow << std::endl;
// using std::match_results
// typedef match_results<string::const_iterator> smatch;
std::smatch smatch;
if ( std::regex_match(official, smatch, regValues)){
std::string textFuture= smatch.format(standardText);
std::cout << std::setw(len) << std::left << "Future: " << textFuture << std::endl;
}
std::cout << std::endl;
}

In the function call std::regex_replace(unofficial, regValues, standardText) ...