繁体   English   中英

如何在无符号字符数组上执行正则表达式? C++

[英]How to do a regex on an unsigned char array? 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 字节顺序存储字符数组的系统上,正则表达式实际上可能不匹配)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM