正则表达式与从 C++ 中的文件加载的长字符串的任何内容都不匹配

Regex doesn't match anything for long strings loaded from file in C++

本文关键字:字符串 任何内 不匹配 文件 C++ 正则表达式 加载      更新时间:2023-10-16

我有一个ascii编码的纯html文件。我在Visual c++ 2012中的c++子程序中加载它,并尝试从中提取一些模式。但是我发现,无论正则表达式是什么,都找不到匹配。

我尝试了cmatch和smatch程序,但它不能与从文件加载的字符串一起工作。

文件只包含ascii字符,我需要多行正则表达式支持,但该程序仅适用于分配的字符串,而不适用于从文件加载的字符串。我检查了文件中载入的文本。加载正确。问题在于正则表达式。

void findFrasi(string filename){
    fstream f;
    f.open(filename, fstream::in);
    char* ls;
    ls = (char*)malloc(1000 * 10); 
    f.get(ls, fileSize, char(255));
    std::string s(ls);
    try {
        //s= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">";
        std::smatch cm;
        std::regex e ("([\s|\S]*)(http)([\s|\S]*)", std::regex::ECMAScript  | std::regex::icase );
        std::regex_match( s, cm, e, regex_constants::match_any );
        std::cout << "matches:" << cm.size() << std::endl;
        for (std::smatch::iterator it = cm.begin(); it!=cm.end(); ++it) {
            std::cout << *it << std::endl;
        }
    } catch (std::regex_error& e) {
        if (e.code() == std::regex_constants::error_badrepeat)
            std::cerr << "Repeat was not preceded by a valid regular expression.n";
        else std::cerr << "Some other regex exception happened.n";
    }
    free(ls);
    f.close();
}

异常永远不会发生!我总是得到输出:matches0

顺便说一下,我也尝试了其他正则表达式脚本,如std::regex::ECMAScript,它们没有什么不同。

您可以使用sregex_iterator获得所有匹配项。

像这样的东西(应该运行在Visual c++ 2012与Nov2012CTP):

#include <regex>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    std::string filepath = "jonny_regex_text.txt"; // the file you provided
    std::ifstream ifs(filepath.c_str(), std::ios_base::in | std::ios_base::binary);
    ifs.seekg(0, std::ios_base::end);
    size_t length = static_cast<size_t>(ifs.tellg());
    ifs.seekg(0, std::ios_base::beg);
    std::string text;
    text.resize(length);
    ifs.read(&text[0], length);
    ifs.close();
    std::string pattern(R"((http|https|ftp)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9-._?,'/\+&amp;%$#=~])*)");
    std::regex r(pattern, regex::icase);
    for (std::sregex_iterator it(text.begin(), text.end(), r), end_it; it != end_it; ++it)
    {
        std::cout << it->str() << std::endl;
    }
    return 0;
}

代码打印文本文件中的所有url。