简体   繁体   中英

Why is my regex causing an infinite loop?

I'm new to the c++ regex library. I noticed while following the documentation on cplusplus.com that in their example, the condition they used to terminate the iteration loop would always return true if I used a regex that matched the entire target sequence. Ideally, the loop should match once and then terminate. Here's my code:

#include <iostream>
#include <regex>

int main()
{
    std::string str("Foo bar");
    std::regex reg("(.|[\r\n])*"); // Match the whole string

    std::regex_iterator<std::string::iterator> rit(str.begin(), str.end(), reg);
    std::regex_iterator<std::string::iterator> rend;

    while (rit != rend) // For some reason this is always true
    {
        std::cout << "Infinite loop!" << std::endl;
        rit++;
    }

    return 0;
}

What am I doing wrong?

Not positive, would have to verify, but I believe your * means 0 or more. So it can match 0 at the end of the string forever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM