【问题标题】:Regex non printable bytes正则表达式不可打印字节
【发布时间】:2016-11-03 23:26:42
【问题描述】:

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

    char cData[1024] = { 0 };
    memcpy(cData, "\x00\x04\x02\x08\x00hello 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”)。

【问题讨论】:

  • 它以什么方式“不起作用”?
  • 打印“nok”!如果我是赖特。前 5 个字节将在第一组匹配,所以“你好,就是这样”在其他组?! (当然,如果匹配的话)
  • 您确定要使用八进制字符文字吗?我最初认为不是,但后来我看到了 \010 以及其他 2 位数字在十六进制 (\xnn) 中相同的事实,所以也许你做到了。
  • 如何忽略前 5 个字节?我改变了我的例子。

标签: c++ regex unicode ascii


【解决方案1】:

这是解决方案:

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

注意事项:

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

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

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

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

【讨论】:

  • 对不起,这也不起作用...'{5}' 重复五次。
  • regex_error(error_escape):表达式包含无效的转义字符或尾随转义。
  • 我正在使用 VC++。如果使用: std::regex r2e("[\x01-\x1F]{5}.*", 10, std::regex_constants::basic);工作正常!注意 '\x01' 但我需要 '\x00'。
  • 不,'\x00' 告诉我“表达式包含无效的转义字符或尾随转义。”
  • 这很奇怪。试试\0
【解决方案2】:

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

感谢迈克的帮助。但是,经过大量调试尝试,我发现其中一个运行良好!

#include <iostream>
#include <string>
#include <regex>

int main()
{
    char cData[1024] = "\x00\x04\x02\x08\x01Haaaaa";// { 0 };
    char cReg[] = "([\0-\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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2014-01-04
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多