Regex不可打印字节

Regex non printable bytes

本文关键字:字节 打印 Regex      更新时间:2023-10-16

如何与非可打印的Unicode或ASCII字节匹配正则表达式?

    char cData[1024] = { 0 };
    memcpy(cData, "x00x04x02x08x00hello thats it", 19);
    std::regex r2e("([\x00-\x1F]){5}(.?)*", std::regex_constants::basic);
    if (std::regex_search((char*)cData, cData+19, r2e))
        printf("ok");
    else
        printf("nok");

我的例子不工作(打印"nok")

解决方案:

std::regex r2e("[x00-x1F]\{5\}.*", 12, std::regex_constants::basic);

指出:

  1. 您需要在[ - ]范围内插入文字字符

  2. {需要在基本正则表达式中进行转义

  3. (.?)*.*效果相同。

  4. 你必须使用这个构造函数,它需要字符串的长度作为另一个参数,因为x00空字符将结束字符串。

这就是解决方案。我使用了错误的'regex_constants'。

谢谢Mike的帮助。但是,经过大量的调试尝试,我发现其中一个工作得很好!

#include <iostream>
#include <string>
#include <regex>
int main()
{
    char cData[1024] = "x00x04x02x08x01Haaaaa";// { 0 };
    char cReg[] = "([-x1F]{5})(.*)";
    int aux[sizeof(cReg)];
    for (int i = 0; i < sizeof(cReg); i++)
    {
        aux[i] = cReg[i];
    }
    std::match_results<char*> mc;
    std::initializer_list<int> list(aux, aux + 14);
    std::regex r2e(cReg,14, std::regex_constants::ECMAScript);
    if (std::regex_match((char*)cData, cData+10, mc, r2e, std::regex_constants::match_default)) {
        for (auto it : mc)
            std::cout << it.str().c_str() << std::endl;
    }
    else {
        std::cout << "NOK" << std::endl;
    }
    std::string name;
    std::cin >> name;
}