c++ - 如何对无符号字符数组执行正则表达式?C++
问题描述
我有一个无符号字符数组,我想对其执行正则表达式,我不想将其创建为字符数组,也不想从中构造 std::string。有什么办法可以用标准库做到这一点?
#include <regex>
std::regex handler("b");
unsigned char data[4] = {'a','b','c','d'};
std::smatch match;
// how to correctly use this function with 'data'?
std::regex_search(std::begin(data),std::end(data),match,handler);
解决方案
玩std::string_view
了一会儿后,我得到了解决方案
#include <iostream>
#include <string_view>
#include <regex>
int main() {
std::regex reg("bc");
unsigned char arry[4] = {'a','b','c','d'};
std::cmatch match;
std::string_view view(reinterpret_cast<char*>(arry));
// matches and prints 1
std::cout << std::regex_search(view.begin(),view.end(), match, reg);
return 0;
}
(请注意,在不以 little-endian 字节顺序存储字符数组的系统上,正则表达式实际上可能不匹配)
推荐阅读
- javascript - 如何停止未定义以停止在评分计算器中弹出
- amazon-web-services - 什么 AWS EC2 实例最适合设置需要处理许多连接和许多小消息的 socket.io websocket?
- timezone - GMail API 一天的使用限制是在哪个时区计算的?
- nginx - Nginx反向代理到Yesod转发的IP地址不起作用
- c++ - 查找由数组的数字组成的最大数字
- r - 使用分隔符将多列连接到新列 Spark R 数据框
- jquery - Jquery:检查表单是否已经提交并验证
- salesforce - Salesforce 表名称
- ios - ARKit:在 Xcode 中跟踪头部上下运动
- haskell - 在这种情况下如何防止类型范围?