Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does changing the order of calling std::regex::str and std::regex::suffix change the behaviour?

Tags:

c++

regex

I've written some working code that prints out every occurrence of 2 vowels in a row.

std::regex x("(a|e|i|o|u){2}");

std::smatch r;

std::string t = some_string;

while (std::regex_search(t, r, x)) {
    std::cout << "match: " << r.str() << '\n';

    t = r.suffix();
}

But when I change the order like this:

while (std::regex_search(t, r, x)) {
    t = r.suffix();

    std::cout << "match: " << r.str() << '\n';
}

it suddenly starts giving random results. I don't see the connection between these 2 lines, and why changing their order would affect anything. Can anyone explain this?

like image 270
God I Am Clown Avatar asked Dec 08 '25 06:12

God I Am Clown


1 Answers

This statement:

    t = r.suffix();

isn't creating a new string object, or changing what string object t denotes, or anything like that; rather, it's mutating the existing string object by copying over the contents of r.suffix().

And r doesn't hold the actual string data; it just holds index information so that the appropriate string data can be extracted from t. Mutating t essentially invalidates the old indices, so you get the wrong string data.

like image 180
ruakh Avatar answered Dec 09 '25 19:12

ruakh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!