使用boost正则表达式匹配二进制数据

3
boost regex能否在给定的二进制输入中匹配二进制数据?
例如:
以二进制形式输入:
0x01 0x02 0x03 0x04 0x05 0x01 0x02 0x03 0x04 0x08 要匹配的二进制表达式:
0x01 0x02 0x03 0x04 在这种情况下,应该匹配2个实例。
非常感谢!
2个回答

0

是的,boost::regex支持二进制。


请查看[问题]和[答案]。 - Shakiba Moshiri

0
你的问题对我来说不够清楚。所以如果这个答案不是你想要的,告诉我,我会删除它。
正则表达式(boost库)比C++强大得多,如屏幕截图所示:

enter image description here

图片来源

当然,如果C++可以做到,Boost也可以做到。
std::regex::iterator

std::string binary( "0x01 0x02 0x03 0x04 0x05 0x01 0x02 0x03 0x04 0x08" );
std::basic_regex< char > regex( "0x01 0x02 0x03 0x04" );
// or
// std::basic_regex< char > regex( "0x01.+?4" );
std::regex_iterator< std::string::iterator > last;
std::regex_iterator< std::string::iterator > begin( binary.begin(), binary.end(), regex );

while( begin != last ){
    std::cout << begin->str() << '\n';
    ++begin;
}  

输出

0x01 0x02 0x03 0x04
0x01 0x02 0x03 0x04  

或者
std::regex_token::iterator

std::string binary( "0x01 0x02 0x03 0x04 0x05 0x01 0x02 0x03 0x04 0x08" );
std::basic_regex< char > regex( " 0x0[58] ?" );
std::regex_token_iterator< std::string::iterator > last;
std::regex_token_iterator< std::string::iterator > begin( binary.begin(), binary.end(), regex, -1 );

while( begin != last ){
    std::cout << *begin << '\n';
    ++begin;
}

输出
与原样相同


使用 Boost

std::string binary( "0x01 0x02 0x03 0x04 0x05 0x01 0x02 0x03 0x04 0x08" );
boost::basic_regex< char > regex( " 0x0[58] ?" );

boost::regex_token_iterator< std::string::const_iterator > last;
boost::regex_token_iterator< std::string::const_iterator > begin( binary.begin(), binary.end(), regex, -1 );

while( begin != last ){
    std::cout << *begin << '\n';
    ++begin;
}  

输出
与原样相同

区别在于:std::string::const_iterator,而不是std::string::iterator


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接