Dylan_Larkin Dylan_Larkin - 1 month ago 18
C++ Question

regex_search and substring matching

Here is my code:

std::string var = "(1,2)";
std::smatch match;
std::regex rgx("[0-9]+");
if(std::regex_search(var,match,rgx))
for (size_t i = 0; i < match.size(); ++i)
std::cout << i << ": " << match[i] << '\n';


I want to be able to extract both 1 AND 2, but so far output is just the first match (1). I can't seem to figure out why and my brain is fried. It's probably something obvious

Answer

regex_match's elements are for matching groups within the regex.

In a slightly modified example

std::string var = "(11b,2x)";
std::smatch match;
std::regex rgx("([0-9]+)([a-z])");
if(std::regex_search(var,match,rgx))
    for (size_t i = 0; i < match.size(); ++i)
        std::cout << i << ": " << match[i] << '\n';

You'd get the following output:

0: 11b
1: 11
2: b

What you want is to use std::regex_iterator to go over all the matches:

auto b = std::sregex_iterator(var.cbegin(), var.cend(), rgx);
auto e = std::sregex_iterator();

std::for_each(b, e, [](std::smatch const& m){
    cout << "match: " << m.str() << endl;
});

This will yield the desired output:

match: 1
match: 2

live demo

Comments