gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:37:16 25 4
gpt4 key购买 nike

我正在阅读一个 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("%s\n",match[0]); // this outputs some garbage like this '˜ò'

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

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

最佳答案

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

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

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

因此,您 promise 通过 %s 进行 TRACE 的内容(即原始 C 字符串 char* 指针)和您实际上传递给它的是什么(即match[0])。

根据 some online documentation , std::smatchstd::match_results 模板的特化,特别是:

smatch --> match_results<string::const_iterator>

smatch::operator[](您在代码中调用的是 match[0])returns a reference to another object ,这是一个 std::sub_match。这std::sub_match class表示一对迭代器,表示匹配字符的序列。

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

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

为此,您可以调用 std::sub_match's str() method .这将返回一个 std::string 对象。

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

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

总结这些逻辑步骤:

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("%s\n", match[0].str().c_str());

关于c++ - 无法检索正则表达式匹配结果 - MFC/C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35347178/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com