Alexander
Alexander

Reputation: 981

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?

Upvotes: 1

Views: 454

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

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.

Upvotes: 2

Related Questions