无法检索正则表达式匹配结果 - MFC / C++

Unable to retrieve regex match results - MFC / C++

本文关键字:MFC C++ 结果 检索 正则表达式      更新时间:2023-10-16

我正在阅读一个HTML页面并试图检索其中的特定字符串。

我有以下代码:

    std::string str = test.GetString(); // someString ( the string i have checked it, it's basically an html page )
    std::smatch match;
    std::regex re("0x(\d|[A-Z]).*0000"); // the pattern I'm searching for
    if (std::regex_search(str, match, re)){
        test = "found"; // found gets printed
    }
    TRACE("%sn",match[0]); // this outputs some garbage like this '˜ò'

我想打印/存储找到的匹配结果,但我得到了一些垃圾。

免责声明:我是C++正则表达式新手。我可能犯了一个基本错误

std::smatch match;
...
TRACE("%sn",match[0]); // this outputs some garbage like this '˜ò'

TRACE宏中的%s类型说明符需要原始 C字符串指针(char* 在 ANSI/MBCS 版本中; wchar_t*在 Unicode 构建中 - 我假设您正在这里进行 ANSI/MBCS 构建。

match[0]不是原始的 C 字符串指针。

因此,您承诺通过%s(即原始 C 字符串char*指针(TRACE与您实际传递给它的内容(即 match[0](。

根据一些在线文档,std::smatchstd::match_results模板的专用化,特别是:

smatch --> match_results<string::const_iterator>

smatch::operator[](您在代码中以 match[0] 形式调用(返回对另一个对象的引用,该对象是一个std::sub_match。此 std::sub_match 类表示一对迭代器,表示匹配字符的序列。

因此,您承诺TRACE传递原始 C 字符串指针(通过 %s 类型说明符(,但您实际上是在传递完全不同的东西,即对std::sub_match对象的引用(通过您的match[0]代码(:难怪打印的文本毫无意义。

您要做的是从match[0]表达式中获取 C 字符串指针。

为此,您可以调用std::sub_matchstr()方法。这将返回一个std::string对象。

但是,这个std::string对象并不完全是%s所期望的:实际上,%s表示一个原始的 C 字符串指针(例如 const char* (,而不是std::string实例。

因此,最后一步是从 std::string 对象中提取此原始 C 字符串指针,这是通过调用 std::string::c_str() 方法完成的。

总结这些逻辑步骤:

std::smatch match;
...
match[0]               --> reference to std::sub_match object
match[0].str()         --> std::string object
match[0].str().c_str() --> raw C string pointer (const char*)

因此,您的TRACE语句可以写为:

TRACE("%sn", match[0].str().c_str());

这里的问题是match[0]返回一个类型为 sub_match 的对象,它只是一对迭代器。如果 TRACE 宏的第一个参数是 C 样式格式说明符,请将sub_match对象转换为 C 字符串,如下所示:

TRACE("%sn", std::string(match[0]).c_str());

也就是说,使用 sub_matchoperator string() 获取(临时(C++字符串对象,然后调用其成员函数 c_str(( 来获取(临时(C 字符串对象。