为什么我的正则表达式会导致无限循环

Why is my regex causing an infinite loop?

本文关键字:无限循环 我的 正则表达式 为什么      更新时间:2023-10-16

我是 c++ regex库的新手。我在关注有关 cplusplus.com 的文档时注意到,在他们的示例中,如果我使用与整个目标序列匹配的正则表达式,他们用于终止迭代循环的条件将始终返回true。理想情况下,循环应匹配一次,然后终止。这是我的代码:

#include <iostream>
#include <regex>
int main()
{
    std::string str("Foo bar");
    std::regex reg("(.|[rn])*"); // 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;
}

我做错了什么?

不是肯定的,必须验证,但我相信你的*意味着 0 或更多。因此,它可以永远匹配字符串末尾的 0。