C++ Academy · Lesson

Search and Replace

Transform text with regex.

Lesson 3 of 413 steps

Search and Replace is a free C++ Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.

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;
}

Backreferences in Replacement

Use $1, $2, ... in the replacement string to insert captured groups, letting you rearrange text.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\w+) (\\w+)");
    std::string s = "John Smith";
    std::cout << std::regex_replace(s, p, "$2 $1") << '\n';
    return 0;
}

The Whole Match: $&

The token $& refers to the entire match, handy for wrapping found text in extra characters.

#include <iostream>
#include <regex>

int main() {
    std::regex p("\\d+");
    std::string s = "item 42";
    std::cout << std::regex_replace(s, p, "[$&]") << '\n';
    return 0;
}

Replace First Only

Pass std::regex_constants::format_first_only to replace only the first match instead of every occurrence.

#include <iostream>
#include <regex>

int main() {
    std::regex p("o");
    std::string s = "foo boo";
    auto out = std::regex_replace(s, p, "0", std::regex_constants::format_first_only);
    std::cout << out << '\n';
    return 0;
}

Normalizing Whitespace

A common cleanup task: collapse runs of whitespace into a single space.

#include <iostream>
#include <regex>

int main() {
    std::regex p("\\s+");
    std::string s = "too    many     spaces";
    std::cout << std::regex_replace(s, p, " ") << '\n';
    return 0;
}

Removing Matches

Replacing with an empty string effectively deletes every match, useful for stripping unwanted characters.

#include <iostream>
#include <regex>

int main() {
    std::regex p("[^a-zA-Z]");
    std::string s = "a1b2c3";
    std::cout << std::regex_replace(s, p, "") << '\n';
    return 0;
}

Reformatting Dates

Capture parts of a date and reorder them in the replacement to change the format.

#include <iostream>
#include <regex>

int main() {
    std::regex p("(\\d{4})-(\\d{2})-(\\d{2})");
    std::string s = "2026-05-30";
    std::cout << std::regex_replace(s, p, "$3/$2/$1") << '\n';
    return 0;
}

Keeping Unmatched Text

By default unmatched text is copied through. Use format_no_copy to output only the replacements and drop the rest.

#include <iostream>
#include <regex>

int main() {
    std::regex p("\\d+");
    std::string s = "a1b2c3";
    auto out = std::regex_replace(s, p, "$&", std::regex_constants::format_no_copy);
    std::cout << out << '\n';
    return 0;
}

Censoring Words

Combine alternation with replacement to censor a list of words at once.

#include <iostream>
#include <regex>

int main() {
    std::regex p("bad|evil");
    std::string s = "a bad and evil idea";
    std::cout << std::regex_replace(s, p, "***") << '\n';
    return 0;
}

Building Up a Result

Because regex_replace returns a string, you can chain transformations by feeding one result into the next call.

#include <iostream>
#include <regex>

int main() {
    std::string s = "  Hello,   World  ";
    s = std::regex_replace(s, std::regex("\\s+"), " ");
    s = std::regex_replace(s, std::regex("^ | $"), "");
    std::cout << "[" << s << "]\n";
    return 0;
}

Quick Check

Test your understanding of replacement syntax.

Recap

You learned to transform text with regex_replace:

  • replaces all matches by default and returns a new string
  • $1, $2, $& insert captures and the whole match
  • flags like format_first_only and format_no_copy
  • chain calls to build complex cleanups

Next, you will learn how to use regex efficiently and avoid common performance traps.

Free to start

Learn C++ with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Search and Replace” lesson free?

Yes — any 3 lessons of the C++ Academy learning path, including “Search and Replace”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.

What will I learn in “Search and Replace”?

Transform text with regex. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

How long does the “Search and Replace” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. regex Basics
  2. Capturing Groups
  3. Search and Replace
  4. Performance Notes
← Back to C++ Academy