Skip to content
C++: Copy repeated regex matches into owned strings

C++: Copy repeated regex matches into owned strings

November 12, 2026

A regex iterator can collect each matching ticket identifier from a note. Copy each match into a string if the results need to survive after the note changes.

Prepare a scratch directory

Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save as cpp-regex-iterator-copy-matches.cpp:

#include <cassert>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

int main() {
    std::string note = "see TASK-12, then TASK-7";
    const std::regex pattern{R"(TASK-[0-9]+)"};
    std::vector<std::string> tickets;
    for (auto it = std::sregex_iterator(note.begin(), note.end(), pattern);
         it != std::sregex_iterator{}; ++it) {
        tickets.push_back(it->str());
    }
    note.clear();
    assert((tickets == std::vector<std::string>{"TASK-12", "TASK-7"}));
    for (const auto& ticket : tickets) std::cout << ticket << '\n';
    const std::string empty;
    assert(std::sregex_iterator(empty.begin(), empty.end(), pattern) ==
           std::sregex_iterator{});
}

Compile and run:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-regex-iterator-copy-matches.cpp -o cpp-regex-iterator-copy-matches &&
./cpp-regex-iterator-copy-matches

Observed output:

TASK-12
TASK-7

How it works

Incrementing the iterator searches for the next non-overlapping match. Both the input and regex stay alive for the entire loop. str() creates an owning string, so clearing the note afterward does not affect the collected tickets.

Limits and choices

This pattern searches substrings: it also finds TASK-12 inside XTASK-12Y. Define surrounding-token rules if that is unwanted. Copying a match-results object alone does not copy the input characters. Keep inputs bounded and avoid untrusted patterns when runtime or memory must be controlled.

The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.

Clean up

rm -- cpp-regex-iterator-copy-matches.cpp cpp-regex-iterator-copy-matches
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect the remaining files before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on