Search and Replace
Transform text with regex.
regex_replace
std::regex_replace returns a new string where every match of a pattern is replaced by a replacement string.
- The original string is left unchanged.
- By default, all matches are replaced.
#include <iostream>
#include <regex>
int main() {
std::regex p("cat");
std::string s = "the cat and the cat";
std::cout << std::regex_replace(s, p, "dog") << '\n';
return 0;
}Replacing Digits
Patterns make bulk edits easy, such as masking every digit in a string with a placeholder.
#include <iostream>
#include <regex>
int main() {
std::regex p("\\d");
std::string s = "PIN 1234";
std::cout << std::regex_replace(s, p, "*") << '\n';
return 0;
}All lessons in this course
- regex Basics
- Capturing Groups
- Search and Replace
- Performance Notes