简体   繁体   中英

std::regex_match() freezes my program

So here is my program:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <regex>
#include <windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string str = "<link rel=\"shortcut icon\" href=\"http://joyvy.com/img/favicon.png\" />";
    regex expr("<link rel=+(\"|')+shortcut+(.*?(\"|'))+(.*?)href=(\"|')+(.*?)+(\"|')");
    smatch matches;

    cout << "start..." << endl;
    regex_match(str, matches, expr);
    cout << "this will not be printed";
}

And here is the output of my program:

start...

The std::regex_match() function call is just freezes my program. After the lapse of 2 or 3 minutes it trows error:

Unhandled exception at at 0x7515B760 in regex.exe: Microsoft C++ exception: std::regex_error at memory location 0x001D9088.

So what's wrong?

Looks like your regular expression is just too complex, and takes forever to process. And the likely reason for that is that you don't seem to understand what + means in a regular expression. You seem to believe it's used for concatenation or something. In fact, it means "the previous element repeated one or more times", similar to * meaning "repeated zero or more times". Drop all the pluses, and the program works.

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