首页 > 解决方案 > 如何对无符号字符数组执行正则表达式?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);

标签: c++

解决方案


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 字节顺序存储字符数组的系统上,正则表达式实际上可能不匹配)


推荐阅读