std::regex_match()冻结我的程序

std::regex_match() freezes my program

本文关键字:冻结 我的 程序 match regex std      更新时间:2023-10-16

这是我的程序:

#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";
}

这是我程序的输出:

start...

函数的std::regex_match()调用只是冻结了我的程序。经过2或3分钟后,它会出现错误:

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

那怎么了?

看起来您的正则表达式太复杂了,处理起来需要很长时间。这可能是因为你似乎不理解+在正则表达式中的含义。你似乎相信它是用来串联或其他什么的。事实上,它的意思是"前一个元素重复了一次或多次",类似于*,意思是"重复了零次或更多次"。去掉所有的优点,程序就会工作。