Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ regex_search is really weird

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading