无法检索正则表达式匹配结果 - MFC / C++
Unable to retrieve regex match results - MFC / C++
我正在阅读一个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::smatch
是std::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_match
的str()
方法。这将返回一个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_match
的 operator string()
获取(临时(C++字符串对象,然后调用其成员函数 c_str(( 来获取(临时(C 字符串对象。
- C++ MFC Libraries in Travis CI
- 从 bmp 文件数据创建 MFC CBitmap
- 如何在 MFC 中显示文件的所有行
- 目录删除 MFC 的问题
- MFC:如何设置CEdit框的焦点?
- MFC 中的抗锯齿
- 双击更改 mfc 中列表控件中的行的颜色
- C++MFC编辑框处理双击
- C++ MFC CObject 派生类摘要?
- 如何在 MFC 对话框中使用 OnDraw
- 在 1 个服务器 n 客户端套接字 C++ MFC 应用程序中更新数据的客户端
- MFC:你能在CDateTimeCtrl中改变自旋的加速度吗?
- MFC:我们如何轻松地从CTreeCtrl切换到CTreeView?
- __int64 CString 返回错误的值 - C++ MFC
- 如何在MFC中的静态文本控件上插入图标?
- 使用 MFC 的表/网格
- MFC 中的窗口消息管理:添加基类调用是否是强制性的?
- MFC/C++ ComboBox:禁用下拉列表关闭和打开(UI 冻结)的绘制
- C++ MFC 跟踪事件调用
- 如何在 MFC 应用程序中启动 ZeroMQ 线程?